簡單的使用者管理

檸檬味的汽水發表於2020-11-08

本系統實現對使用者的增刪改查

使用的技術 JSP+Servlet+MySQL

本系統採用mvc分層模式實現,jsp作為前端頁面展示,serlvet實現控制層效果,mysql實現資料儲存。

實體類bean

public class User {
    private static final long serialVersionUID = 1L;
    private int id;
    private String username;
    private String password;

    public User() {

    }

    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }


    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

工具類DBUtil

public class DBUtil {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/t_user?useUnicode=true&characterEncoding=UTF-8" +
                "&useSSL=false&serverTimezone=GMT%2B8";
        String username = "root";
        String password = "root";
        try {
            conn = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

資料訪問層 dao

public class UserDAO {
    //查詢使用者列表
    public List<User> showUsers() throws Exception {
        List<User> users = new ArrayList<>();
        ResultSet rs;
        Connection conn = DBUtil.getConnection();
        String sql = "select * from user";
        PreparedStatement psmt = conn.prepareStatement(sql);
        rs = psmt.executeQuery();
        while (rs.next()) {
            int id = rs.getInt("id");
            String username = rs.getString("username");
            String password = rs.getString("password");
            User user = new User(id,username,password);
            users.add(user);
            //System.out.println(users);
        }
        DBUtil.closeConnection(conn);
        return users;
    }

    //查詢一個使用者資訊
    public User getUser(int id) {
        User user = new User();
        Connection conn = DBUtil.getConnection();
        ResultSet rs;
        String sql = "select * from user where id = ?";
        PreparedStatement psmt = null;
        try {
            psmt = conn.prepareStatement(sql);
            psmt.setInt(1, id);
            rs = psmt.executeQuery();
            while (rs.next()) {
                String username = rs.getString("username");
                String password = rs.getString("password");
                user.setUsername(username);
                user.setPassword(password);
                user.setId(id);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DBUtil.closeConnection(conn);
        return user;
    }
        //新增使用者
    public int insertUser(User user) {
        int flag = 0;
        Connection conn = DBUtil.getConnection();
        String sql = "insert into user (username, password) values (?,?)";
        PreparedStatement psmt = null;
        try {
            psmt = conn.prepareStatement(sql);
            psmt.setString(1, user.getUsername());
            psmt.setString(2, user.getPassword());
            flag = psmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DBUtil.closeConnection(conn);
        return flag;
    }

    // 修改使用者
    public void updateUser(User user) {
        Connection conn = DBUtil.getConnection();
        String sql = "update user set username = ?, password = ? where id = ?";
        PreparedStatement psmt;
        try {
            psmt = conn.prepareStatement(sql);
            psmt.setString(1, user.getUsername());
            psmt.setString(2, user.getPassword());
            psmt.setInt(3, user.getId());
            psmt.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DBUtil.closeConnection(conn);
    }


    public void deleteUser(int id) {
        Connection conn = DBUtil.getConnection();
        String sql = "delete from user  where id = ?";
        PreparedStatement psmt;
        try {
            psmt = conn.prepareStatement(sql);
            psmt.setInt(1,id);
            psmt.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DBUtil.closeConnection(conn);
    }
}

服務層 service

public class UserService {
    private UserDAO userDAO = new UserDAO();
    // 查詢使用者列表
    public List<User> showUsers() {
        try {
            return userDAO.showUsers();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 查詢單個使用者
    public User getUserById(int id) {
            return userDAO.getUser(id);
    }

    // 新增使用者
    public int insertUser(User user)  {
        return userDAO.insertUser(user);
    }

    // 修改使用者
    public void updateUser(User user) {
        userDAO.updateUser(user);
    }

    // 刪除使用者
    public void deleteUser(int id) {
        userDAO.deleteUser(id);
    }

}

控制層 controller

@WebServlet("/jsp/AddUserServlet")
public class AddUserServlet extends HttpServlet {
    private UserService userService = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 從前端頁面獲取到使用者名稱和密碼
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 建立一個使用者,並新增使用者名稱和密碼
        User user = new User(username,password);
        int flag = userService.insertUser(user);
        System.out.println(user.toString());
        System.out.println(flag);
        if (flag != 0) {
            // 跳轉到UserServlet
            response.sendRedirect("UserServlet");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
@WebServlet("/jsp/DeleteUserServlet")
public class DeleteUserServlet extends HttpServlet {
    private UserService userService = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 從前端頁面獲取id
        int id = Integer.parseInt(request.getParameter("id"));
        // 根據id呼叫 userService.getUserById方法刪除使用者
        userService.deleteUser(id);
        // 跳轉到UserServlet
        response.sendRedirect("UserServlet");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

 

@WebServlet("/jsp/EditUserServlet")
public class EditUserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private UserService userService = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 從前端頁面獲取id,username,password
        int id = Integer.parseInt(request.getParameter("id"));
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User(id,username, password);
        // 設定使用者
        userService.updateUser(user);
        System.out.println(user.toString());
        // 跳轉到UserServlet
        response.sendRedirect("UserServlet");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 從前端頁面獲取id
        int id = Integer.parseInt(request.getParameter("id"));
        // 根據id呼叫 userService.getUserById方法查詢使用者
        User user = userService.getUserById(id);
        request.setAttribute("user",user);
        System.out.println(user.toString());
        // 跳轉到/jsp/edit_user.jsp
        request.getRequestDispatcher("/jsp/edit_user.jsp").forward(request, response);
    }
}
@WebServlet("/jsp/UserServlet")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> users = userService.showUsers();
        request.getSession().setAttribute("users",users);
        request.getRequestDispatcher("/jsp/user.jsp").forward(request,response);
     }
}

前端頁面

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
    <title>新增使用者</title>
</head>
<body>
<h3>新增使用者</h3>
    <form action="AddUserServlet" method="post">
        <table>
            <tr>
                <td>使用者名稱:</td>
                <td><input type="text" name="username"></td>
            </tr>

            <tr>
                <td>密碼:</td>
                <td><input type="password" name="password"></td>
            </tr>

            <tr>
                <td colspan="2" align="right">
                    <input type="reset" value="重置">
                    <input type="submit" value="提交">
                </td>
            </tr>
        </table>
    </form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<html>
<head>
    <title>修改使用者</title>
</head>
<body>
<h3>修改使用者</h3>
<form action="EditUserServlet" method="post">
    <table>
        <input type="hidden" name="id" value="${user.id}">
        <tr>
            <td>使用者名稱:</td>
            <td><input type="text" name="username" value="${user.username}"></td>
        </tr>

        <tr>
            <td>密碼:</td>
            <td><input type="password" name="password" value="${user.password}"></td>
        </tr>

        <tr>
            <td colspan="2" align="right">
                <input type="reset" value="重置">
                <input type="submit" value="提交">
            </td>
        </tr>
    </table>
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>使用者列表</title>
</head>
<body>
    <table border="1" cellpadding="15" cellspacing="0">
        <tr>
            <th>使用者id</th>
            <th>使用者名稱</th>
            <th>密碼</th>
            <td>操作&nbsp;|&nbsp;<button onclick="window.location.href='add_user.jsp'">新增</button></td>
        </tr>
        <c:forEach items="${sessionScope.users}" var="user">
            <tr>
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.password}</td>
                <td>
                    <a href="${pageContext.request.contextPath}/jsp/EditUserServlet?id=${user.id}">修改</a>
                    &nbsp;|&nbsp;
                    <a href="${pageContext.request.contextPath}/jsp/DeleteUserServlet?id=${user.id}">刪除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

經過不斷地修改,最終系統還是達到預期的效果,其中有一些坎坷還是有必要說明一下。其它的功能都沒有什麼問題,但是在修改使用者資料的時候,出現了一個邏輯錯誤。

就是不知道在修改使用者資料的時候,資料回顯和修改使用者如何做,最後通過慢慢嘗試,最後還是做出來了。

寫在最後:路漫漫其修遠兮,吾將上下而求索。

 

相關文章