Address book management system based on Java and MySQL development

832201303朱纪钧 2024-10-31 18:48:38

Address book management system based on Java and MySQL development

Course for This AssignmentEE308FZ Software Engineering
Name and FZU ID朱纪钧_832201303
Assignment DescriptionMake an address book system with separated front and back ends
Objectives of This Assignment1.Separate the front and back ends
2.Add, modify, and delete contacts
Other References1. 构建之法——现代软件工程 阅读笔记
2. 黑马程序员最新版JavaWeb综合案例
Git Repository Link前端:https://github.com/Delphinim/Assignment1_Front.git
后端:https://github.com/Delphinim/Assignment1_Back.git
The Cloud Server Access Linkhttp://localhost:6060/login.jsp
Code Standards Link1. Java语言编程规范
2. Web标准(网页标准)

目录

  • Address book management system based on Java and MySQL development
  • 1. Assignment Description
  • 2. PSP table
  • 3. Function Analysis And Design Of The Implementation Process
  • 3.1 Demand analysis
  • 3.2 System architecture design
  • 3.3 Database design
  • 3.4 Back-end implementation:
  • 3.5 Front-end implementation:
  • 3.6 Functional structure diagram
  • 4. Coding Implementation
  • 4.1 Frontend Page Presentation
  • Function 1:Add
  • Function 2:Modify
  • Function 3:Delete
  • Extended Function 4:User login
  • 4.2 Backend Functionality Implementation
  • 1. Database
  • 2. Add
  • 3. Modify
  • 4. Delete
  • 5. Personal Journey and Learnings

1. Assignment Description

The address book project is based on the Java Web framework and provides basic contact management functions, including adding, modifying, and deleting contacts. Contact information is stored and manipulated through a back-end database to ensure real-time and consistent data. In addition, the project also designed the user login function, users can log in to the system through the account and password for management operations, to further improve the security of data and user experience.

2. PSP table

Personal Software Process StagesEstimated time (minutes)Actual time (minutes)
Planning450565
Demand analysis3025
Learn Java and MySQL360480
Generate design document6060
Development360420
Back-end database establishment6060
Front-end development and interface design180240
Connected the front and back ends of the software120120
Test6030
Total8701015

3. Function Analysis And Design Of The Implementation Process

3.1 Demand analysis

User management: Provides the user login function to ensure that only authorized users can access contact information.

Contact management: Allows you to add, modify, delete, and query contact information.

Data persistence: The contact information is stored in the database to achieve persistent data management.

Front-end interface: User-friendly page design for contact management.

3.2 System architecture design

The system adopts the classic MVC architecture of Java Web (Model-View-Controller), with a clear structure and clear responsibilities:

Model layer: It is responsible for interacting with the database and using JavaBean and JDBC to implement the operation of adding, deleting, modifying and checking data.

View layer: Based on JSP technology, it is mainly responsible for page display, form submission and front-end form verification.

Controller layer: Processes client requests through Java servlets, invokes Model layer according to business logic, and returns processing results to View layer.

3.3 Database design

Use Mysql to create databases and corresponding tables to store user and contact information:

User table: Stores information such as user accounts and passwords for authentication.

Contacts: Stores basic information such as the name, gender, address, and phone number of the contact.

3.4 Back-end implementation:

JavaBean: Defines the User and Contact JavaBean classes for storing and managing data objects.

DAO layer: Create UserDao and ContactDao, and use JDBC to implement database addition, deletion, change and check operations.

Servlet controller: Implements AddServlet, UpdateServlet, DeleteServlet, etc., controls request forwarding, handles contact management and user authentication logic.

3.5 Front-end implementation:

JSP pages: Build login.jsp, add.jsp, edit.jsp and other pages to display data and provide user interface.

CSS and Bootstrap: Introduces Bootstrap and custom CSS files to provide uniform layouts and styles.

JavaScript and jQuery: Provides front-end validation for forms to ensure that submitted data is formatted.

3.6 Functional structure diagram

img

4. Coding Implementation

4.1 Frontend Page Presentation

img

Function 1:Add

img

Function 2:Modify

img

Function 3:Delete

img

Extended Function 4:User login

img

4.2 Backend Functionality Implementation

1. Database

The BookDao class is a Java DAO (data access object) that manipulates the "book" table in the database. This class connects to the database through JDBC and provides multiple methods to add, delete, modify, and query contact information:

Selectbook() : query all contact information and return a list of contacts.
Addbook(book) : add new contact records and insert contact information into the database.
Updatebook(book) : update the contact information according to the contact id.
Deletebook(int bookid) : delete the corresponding record according to the contact id.
Getbookbyid(int bookid) : query the contact id and return the details.
Getbookname(string bookname) : query the name and return the list of eligible contacts.

Through these methods, the bookdao class provides the basic operating interface for the number of couplets, and applies to the back end of the contact management system.

package dao;

import bean.Book;
import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDao {

    /**
     * 所有学生信息
     *
     * @return
     */
    public List<Book> selectBook() {
        List<Book> bookList = new ArrayList<>();

        String sql = "select * from book";
        try {
            Connection conn = DBUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement(sql);
            ResultSet rst = pst.executeQuery();
            while (rst.next()) {
                Book book = new Book();
                book.setBookId(rst.getInt("book_id"));
                book.setBookName(rst.getString("book_name"));
                book.setBookSex(rst.getInt("book_sex"));
                book.setBookAdd(rst.getString("book_add"));
                book.setBookTel(rst.getString("book_tel"));
                bookList.add(book);
            }
            rst.close();
            pst.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return bookList;
    }

    /**
     * 添加学生
     *
     * @param book
     * @return
     */
    public boolean addBook(Book book) {
        String sql = "INSERT INTO book(book_name,book_sex,book_add,book_tel) VALUES(?,?,?,?);";

        try {
            Connection conn = DBUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setString(1, book.getBookName());
            pst.setInt(2, book.getBookSex());
            pst.setString(3, book.getBookAdd());
            pst.setString(4, book.getBookTel());
            int count = pst.executeUpdate();
            pst.close();
            return count > 0 ? true : false;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 修改学生信息
     *
     * @param book
     * @return
     */
    public boolean updateBook(Book book) {
        String sql = "UPDATE book set book_name=?,book_sex=?,book_add=?,book_tel=? WHERE book_id=?";

        try {
            Connection conn = DBUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setString(1, book.getBookName());
            pst.setInt(2, book.getBookSex());
            pst.setString(3, book.getBookAdd());
            pst.setString(4, book.getBookTel());
            pst.setInt(5, book.getBookId());
            int count = pst.executeUpdate();
            pst.close();
            return count > 0 ? true : false;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除学生信息
     *
     * @param bookId
     * @return
     */
    public boolean deleteBook(int bookId) {
        String sql = "delete from book where book_id = ?";

        try {
            Connection conn = DBUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setInt(1, bookId);
            int count = pst.executeUpdate();
            pst.close();
            return count > 0 ? true : false;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 更具id查询学生
     *
     * @param bookId
     * @return
     */
    public Book getBookById(int bookId) {

        String sql = "select * from book where book_id = " + bookId;
        Book book = new Book();
        try {
            Connection conn = DBUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement(sql);
            ResultSet rst = pst.executeQuery();
            while (rst.next()) {
                book.setBookId(rst.getInt("book_id"));
                book.setBookName(rst.getString("book_name"));
                book.setBookSex(rst.getInt("book_sex"));
                book.setBookAdd(rst.getString("book_add"));
                book.setBookTel(rst.getString("book_tel"));
            }
            rst.close();
            pst.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return book;
    }

    //条件查询
    public List<Book> getBookName(String bookName) {
        List<Book> list = new ArrayList<>();

        String sql = " select * from book where book_name =" + bookName;
        Book book = new Book();
        try {
            Connection conn = DBUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement(sql);
            ResultSet rst = pst.executeQuery();
            while (rst.next()) {
                book.setBookId(rst.getInt("book_id"));
                book.setBookName(rst.getString("book_name"));
                book.setBookSex(rst.getInt("book_sex"));
                book.setBookAdd(rst.getString("book_add"));
                book.setBookTel(rst.getString("book_tel"));
                list.add(book);
            }
            rst.close();
            pst.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}

2. Add

Back end

The AddServlet class is a Java Web component for contact management that is responsible for adding contact information. It provides a form page (via the doGet method) for the user to fill in contact information and handles POST requests for form submissions (via the doPost method). In the doPost method, the class takes the contact information from the request, creates a contact object Book, and stores the contact information into the database via the BookDao data access object. This Servlet implements the core functionality of adding contacts to the system and supports subsequent data storage and management.

package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Book;
import dao.BookDao;

import java.io.IOException;

@WebServlet("/add")
@SuppressWarnings("serial")
public class AddServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("add.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Book book = new Book();
        String bookName = req.getParameter("bookName");
        int bookSex = Integer.parseInt(req.getParameter("bookSex"));
        String bookAdd = req.getParameter("bookAdd");
        String bookTel = req.getParameter("bookTel");
        book.setBookTel(bookTel);
        book.setBookName(bookName);
        book.setBookAdd(bookAdd);
        book.setBookSex(bookSex);
        BookDao bookDao = new BookDao();
        bookDao.addBook(book);
        req.getRequestDispatcher("").forward(req, resp);
    }
}

Front end
This JSP page code implements a form interface for adding contacts. The user can enter the basic information of the contact (name, gender, address, phone number) and click the "confirm add" button to submit the data. The form sends data to the server /add path through POST request, and the corresponding Servlet processes and stores the data into the database to realize the addition function of contact information.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
    <head>
        <meta charset="utf-8">
        <title>联系人管理系统</title>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    </head>

    <body style="padding-top: 20px;">
        <div class="container">
            <div class="col-md-8 col-md-offset-2">
                <h1>添加联系人</h1><br>
                <form action="add" method="post">
                    <div class="form-group">
                        <label>联系人姓名</label>
                        <input type="text" class="form-control" name="bookName">
                    </div>
                    <div class="form-group">
                        <label class="radio-inline">
                            <input type="radio" name="bookSex" value="1" checked="checked"></label>
                        <label class="radio-inline">
                            <input type="radio" name="bookSex" value="0"></label>
                    </div>
                    <div class="form-group">
                        <label>地址</label>
                        <input type="text" class="form-control" name="bookAdd">
                    </div>
                    <div class="form-group">
                        <label>电话</label>
                        <input type="text" class="form-control" name="bookTel">
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-info" >确认添加</button>
                    </div>
                </form>
            </div>
        </div>
    </body>
</html>

3. Modify

Back end

UpdateServlet handles the updating of the contact information. When the user requests a page update, the doGet method retrieves the information for the specified contact and displays it in the update.jsp page. When the user submits the modified information, the doPost method receives the new data and updates the contact records in the database. This Servlet enables the contact management system to flexibly update the information of existing contacts, improving the system availability and user experience.

package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Book;
import dao.BookDao;

import java.io.IOException;

@WebServlet("/update")
@SuppressWarnings("serial")
public class UpdateServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int bookId = Integer.parseInt(req.getParameter("bookId"));
        BookDao bookDao = new BookDao();
        Book book = bookDao.getBookById(bookId);
        req.setAttribute("book", book);
        req.getRequestDispatcher("update.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Book book = new Book();
        int bookId = Integer.parseInt(req.getParameter("bookId"));
        String bookName = req.getParameter("bookName");
        int bookSex = Integer.parseInt(req.getParameter("bookSex"));
        String bookAdd = req.getParameter("bookAdd");
        String bookTel = req.getParameter("bookTel");
        book.setBookId(bookId);
        book.setBookTel(bookTel);
        book.setBookName(bookName);
        book.setBookAdd(bookAdd);
        book.setBookSex(bookSex);
        BookDao bookDao = new BookDao();
        bookDao.updateBook(book);
        req.getRequestDispatcher("").forward(req, resp);
    }
}

Front End

This JSP page presents a form for modifying the contact information, dynamically loading existing information and allowing the user to edit it. Each field of the form gets the current contact information from the book object and is rendered conditionally by JSTL tags. Finally, the form is submitted to /update to process the update. This page combines the Bootstrap style to ensure a nice, clean interface while providing intuitive contact editing.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>

    <head>
        <meta charset="utf-8">
        <title>联系人管理系统</title>
        <link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
    </head>

    <body style="padding-top: 20px;">
        <div class="container">
            <div class="col-md-8 col-md-offset-2">
                <h1>修改联系人</h1><br>
                <form action="/update" method="post">
                    <div class="form-group">
                        <label>编号</label>
                        <input type="text" class="form-control" name=bookId value="${book.bookId}">
                    </div>
                    <div class="form-group">
                        <label>联系人姓名</label>
                        <input type="text" class="form-control" name="bookName" value="${book.bookName}">
                    </div>
                    <div class="form-group">
                        <c:choose>
                            <c:when test="${book.bookSex == 1}">
                                <label class="radio-inline">
                                    <input type="radio" name="bookSex" id="bookSex" value="1" checked="checked"></label>
                                <label class="radio-inline">
                                    <input type="radio" name="bookSex" id="bookSex" value="0"></label>
                            </c:when>
                            <c:when test="${book.bookSex == 0}">
                                <label class="radio-inline">
                                    <input type="radio" name="bookSex" id="bookSex" value="1"></label>
                                <label class="radio-inline">
                                    <input type="radio" name="bookSex" id="bookSex" value="0" checked="checked"></label>
                            </c:when>
                        </c:choose>
                    </div>
                    <div class="form-group">
                        <label>地址</label>
                        <input type="text" class="form-control" name="bookAdd" value="${book.bookAdd}">
                    </div>
                    <div class="form-group">
                        <label>联系人电话</label>
                        <input type="text" class="form-control" name="bookTel" value="${book.bookTel}">
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-info">确认修改</button>
                    </div>
                </form>
            </div>
        </div>
    </body>

</html>

4. Delete

Back End

The DeleteServlet class is a Servlet that deletes contact information, receives the contact ID passed by the client, and deletes the corresponding record through a BookDao call to the database. This class handles GET and POST requests, ensuring that the deletion logic can be performed even if the contact information is accessed/deleted in different ways, and finally the contact information can be removed.

package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BookDao;


import java.io.IOException;

@WebServlet("/delete")
@SuppressWarnings("serial")
public class DeleteServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int bookId = Integer.parseInt(req.getParameter("bookId"));
        BookDao bookDao = new BookDao();
        bookDao.deleteBook(bookId);
        req.getRequestDispatcher("").forward(req, resp);
    }
}

Front End

The confirmd() function pops up a confirmation window when the "delete" button is clicked to ensure that the user confirms the deletion operation. If the user clicks "OK", return true to perform the deletion operation, otherwise return false to cancel the operation.

        <script type="text/javascript">
            function confirmd() {
                var msg = "您真的确定要删除吗?";
                if (confirm(msg)==true){
                    return true;
                }else{
                    return false;
                }
            }
        </script>        <script type="text/javascript">
            function confirmd() {
                var msg = "您真的确定要删除吗?";
                if (confirm(msg)==true){
                    return true;
                }else{
                    return false;
                }
            }
        </script>

5. Personal Journey and Learnings

In developing the contact management system, I embarked on a detailed journey into Java EE, JSP, and web-based database interactions. At the start, my understanding of servlet handling and JSP was foundational; I knew the basics, but implementing a full application felt like a significant challenge. This project taught me how to combine multiple technologies effectively to create a seamless and user-friendly application.

Starting with the backend, I worked on creating servlets for handling CRUD operations—Add, Modify, and Delete. Each servlet needed to manage HTTP requests and interact with the BookDao to process data. Building this logic was a deep dive into understanding request forwarding, encoding handling, and maintaining session state across different operations. Moving onto the JSP layer, I applied JSTL to dynamically render user data, offering functionality like filtering and sorting the list based on attributes like gender. Integrating Bootstrap with custom styling for the user interface design allowed me to appreciate the balance between backend functionality and frontend aesthetics.

One of the most impactful lessons was implementing user safety with JavaScript, like adding delete confirmation dialogs to prevent accidental deletions. This small addition helped me see the importance of usability and security, even in seemingly minor details. Ultimately, this project provided a hands-on perspective on web application development, teaching me not only technical skills but also the value of creating efficient, user-centered applications.

...全文
66 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

170

社区成员

发帖
与我相关
我的任务
社区描述
2401_MU_SE_FZU
软件工程 高校
社区管理员
  • FZU_SE_TeacherL
  • 助教-吴可仪
  • 助教-孔志豪
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧