部门员工管理系统(下)

四 程序代码及运行效果

4.1 登录界面

获取数据库连接:

package com.xxxx.Servlet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBC {
    private static Connection conn = null;

    private static String Name = "root";
    private static String password = "123456";
    private static String URL = "jdbc:mysql://127.0.0.1:3306/department_management?serverTimezone=GMT%2B8&useSSL=false";

    private static String Dname = "com.mysql.jdbc.Driver"; //驱动名

    public static Connection getConn() {
        // 加载驱动
        try {
            Class.forName(Dname);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //获取连接
        try {
            conn = DriverManager.getConnection(URL, Name, password);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }

    public static void main(String[] args) {

        System.out.println(getConn());
    }
}

后端实现:

package com.xxxx.Servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            // 获取数据库连接
            conn = JDBC.getConn();

            // 查询数据库中是否存在匹配的用户名和密码
            String sql = "SELECT * FROM login WHERE userName = ? AND userPwd = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            stmt.setString(2, password);
            rs = stmt.executeQuery();

            if (rs.next()) {
                // 登录成功,将用户名和角色保存到 session 中
                String role = rs.getString("role");
                request.getSession().setAttribute("username", username);
                request.getSession().setAttribute("role", role);

                // 根据角色跳转到不同的页面
                if ("管理员".equals(role)) {
                    response.sendRedirect("index.jsp");
                } else if ("员工".equals(role)) {
                    response.sendRedirect("employee.jsp");
                } else {
                    response.sendRedirect("login.jsp");
                }
            } else {
                // 登录失败,重定向回登录页面,并给出提示
                request.setAttribute("errorMessage", "用户名或密码错误");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) { }
            try { if (stmt != null) stmt.close(); } catch (Exception e) { }
            try { if (conn != null) conn.close(); } catch (Exception e) { }
        }
    }
}

前端页面:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
    <style>
        body {
            background: url('images/04.png') no-repeat center center fixed;
            background-size: cover;
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .login-box {
            background-color: #ffffff;
            padding: 40px 60px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            text-align: center;
            width: 320px;
        }
        .login-box h2 {
            margin-bottom: 20px;
            font-size: 24px;
            color: #333;
        }
        .login-box input[type="text"],
        .login-box input[type="password"] {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #fafafa;
        }
        .login-box input[type="checkbox"] {
            margin-right: 10px;
        }
        .login-box .buttons {
            margin-top: 20px;
        }
        .login-box button {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            background-color: #0288d1;
            color: white;
            font-size: 16px;
        }
        .login-box button:hover {
            background-color: #0277bd;
        }
        .login-box a {
            display: block;
            margin-top: 10px;
            color: #0288d1;
            text-decoration: none;
        }
        .login-box a:hover {
            text-decoration: underline;
        }
        .error-message {
            color: red;
            margin-top: 10px;
        }
    </style>
</head>
<body>
<div class="login-box">
    <h2>登录</h2>
    <form action="LoginServlet" method="post">
        <div>
            <label for="username">账号:</label><br>
            <input type="text" id="username" name="username" required><br>
        </div>
        <div>
            <label for="password">密码:</label><br>
            <input type="password" id="password" name="password" required><br>
        </div>
        <div>
            <label for="remember">
                <input type="checkbox" id="remember" name="remember"> 记住我
            </label><br>
        </div>
        <div class="buttons">
            <button type="submit">登录</button>
            <button type="reset">重置</button>
        </div>
    </form>
    <% if (request.getAttribute("errorMessage") != null) { %>
    <p class="error-message"><%= request.getAttribute("errorMessage") %></p>
    <% } %>
</div>
</body>
</html>

4.2 管理员界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>管理员首页</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: url('images/05.png') no-repeat center center fixed;
            background-size: cover;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0;
            padding: 0;
            height: 100vh;
        }
        .container {
            background-color: #ffffff;
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            text-align: center;
            max-width: 400px;
            width: 100%;
        }
        .container h1 {
            font-size: 24px;
            color: #333;
            margin-bottom: 20px;
        }
        .button {
            padding: 15px 30px;
            margin: 10px 0;
            background-color: #007bff;
            color: #ffffff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            width: 100%;
            font-size: 16px;
        }
        .button:hover {
            background-color: #0056b3;
        }
        .back-button {
            background-color: #6c757d;
        }
        .back-button:hover {
            background-color: #5a6268;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>欢迎<%= request.getSession().getAttribute("username") %>管理员!</h1>
    <button class="button" onclick="location.href='DepartmentServlet'">部门管理</button>
    <button class="button" onclick="location.href='EmployeeServlet'">员工管理</button>
    <button class="button" onclick="location.href='TaskServlet'">任务管理</button>
    <button class="button" onclick="location.href='ViewTasksServlet'">任务查看</button>
    <button class="button back-button" onclick="location.href='login.jsp'">返回登录页面</button>
</div>
</body>
</html>

4.3 部门管理界面

 后端实现:

package com.xxxx.Servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DepartmentServlet")
public class DepartmentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = JDBC.getConn();
        Statement stmt = null;
        ResultSet rs = null;

        try {
            String action = request.getParameter("action");
            if ("delete".equals(action)) {
                int id = Integer.parseInt(request.getParameter("id"));
                deleteDepartment(conn, id);
                response.sendRedirect("DepartmentServlet");
                return;
            } else if ("edit".equals(action)) {
                int id = Integer.parseInt(request.getParameter("id"));
                String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
                String description = new String(request.getParameter("description").getBytes("ISO-8859-1"), "UTF-8");
                updateDepartment(conn, id, name, description);
                response.sendRedirect("DepartmentServlet");
                return;
            } else if ("add".equals(action)) {
                String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
                String description = new String(request.getParameter("description").getBytes("ISO-8859-1"), "UTF-8");
                addDepartment(conn, name, description);
                response.sendRedirect("DepartmentServlet");
                return;
            }

            String search = request.getParameter("search");
            if (search != null && !search.isEmpty()) {
                searchDepartments(conn, request, search);
            } else {
                listDepartments(conn, request);
            }

            request.getRequestDispatcher("department_management.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) { }
            try { if (stmt != null) stmt.close(); } catch (Exception e) { }
            try { if (conn != null) conn.close(); } catch (Exception e) { }
        }
    }

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

    private void deleteDepartment(Connection conn, int id) throws Exception {
        String sql = "DELETE FROM department WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        }
    }

    private void updateDepartment(Connection conn, int id, String name, String description) throws Exception {
        String sql = "UPDATE department SET name = ?, description = ? WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setString(2, description);
            pstmt.setInt(3, id);
            pstmt.executeUpdate();
        }
    }

    private void addDepartment(Connection conn, String name, String description) throws Exception {
        String sql = "INSERT INTO department (name, description) VALUES (?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setString(2, description);
            pstmt.executeUpdate();
        }
    }

    private void listDepartments(Connection conn, HttpServletRequest request) throws Exception {
        Statement stmt = conn.createStatement();
        String sql = "SELECT * FROM department";
        ResultSet rs = stmt.executeQuery(sql);

        StringBuilder departments = new StringBuilder();
        departments.append("<table border='1'>");
        departments.append("<tr><th>ID</th><th>Name</th><th>Description</th><th>操作</th></tr>");

        while (rs.next()) {
            int id = rs.getInt("id");
            departments.append("<tr>");
            departments.append("<td>").append(id).append("</td>");
            departments.append("<td>").append(rs.getString("name")).append("</td>");
            departments.append("<td>").append(rs.getString("description")).append("</td>");
            departments.append("<td>")
                    .append("<button class='button' onclick=\"location.href='department_edit.jsp?id=").append(id).append("&name=").append(rs.getString("name")).append("&description=").append(rs.getString("description")).append("'\">修改</button>")
                    .append("<button class='button' onclick=\"location.href='DepartmentServlet?action=delete&id=").append(id).append("'\">删除</button>")
                    .append("</td>");
            departments.append("</tr>");
        }
        departments.append("</table>");
        request.setAttribute("departments", departments.toString());
    }

    private void searchDepartments(Connection conn, HttpServletRequest request, String search) throws Exception {
        String sql = "SELECT * FROM department WHERE id = ? OR name LIKE ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, search);
            pstmt.setString(2, "%" + search + "%");
            ResultSet rs = pstmt.executeQuery();

            StringBuilder departments = new StringBuilder();
            departments.append("<table border='1'>");
            departments.append("<tr><th>ID</th><th>Name</th><th>Description</th><th>操作</th></tr>");

            while (rs.next()) {
                int id = rs.getInt("id");
                departments.append("<tr>");
                departments.append("<td>").append(id).append("</td>");
                departments.append("<td>").append(rs.getString("name")).append("</td>");
                departments.append("<td>").append(rs.getString("description")).append("</td>");
                departments.append("<td>")
                        .append("<button class='button' onclick=\"location.href='department_edit.jsp?id=").append(id).append("&name=").append(rs.getString("name")).append("&description=").append(rs.getString("description")).append("'\">修改</button>")
                        .append("<button class='button' onclick=\"location.href='DepartmentServlet?action=delete&id=").append(id).append("'\">删除</button>")
                        .append("</td>");
                departments.append("</tr>");
            }
            departments.append("</table>");
            request.setAttribute("departments", departments.toString());
        }
    }
}

前端页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>部门管理</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: Arial, sans-serif;
            background: url('images/05.png') no-repeat center center fixed;
            background-size: cover;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 80%;
            max-width: 900px;
            overflow: hidden;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 12px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .button {
            padding: 10px 20px;
            margin: 5px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            text-decoration: none;
        }
        .button:hover {
            background-color: #0056b3;
        }
        .search-form {
            margin-top: 20px;
            display: flex;
            align-items: center;
        }
        .search-form input[type="text"] {
            padding: 10px;
            flex: 1;
            border: 1px solid #ddd;
            border-radius: 3px 0 0 3px;
            outline: none;
        }
        .search-form button {
            padding: 10px 20px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 0 3px 3px 0;
            cursor: pointer;
        }
        @media only screen and (max-width: 600px) {
            .container {
                width: 95%;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <h2>部门管理</h2>
    <div class="button-group">
        <a href="department_add.jsp" class="button">添加部门</a>
        <a href="index.jsp" class="button">返回</a>
    </div>
    <form method="get" action="DepartmentServlet" class="search-form">
        <input type="text" name="search" placeholder="输入部门ID或名称查询">
        <button type="submit" class="button">查询</button>
    </form>
    <div id="departmentList">
        ${departments} <!-- 显示从 DepartmentServlet 传递过来的部门数据 -->
    </div>
</div>
</body>
</html>

 4.4 员工管理页面

 后端实现:

package com.xxxx.Servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/EmployeeServlet")
public class EmployeeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = JDBC.getConn();
        Statement stmt = null;
        ResultSet rs = null;

        try {
            String action = request.getParameter("action");
            if ("delete".equals(action)) {
                int id = Integer.parseInt(request.getParameter("id"));
                deleteEmployee(conn, id);
                response.sendRedirect("EmployeeServlet");
                return;
            } else if ("edit".equals(action)) {
                int id = Integer.parseInt(request.getParameter("id"));
                String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
                int departmentId = Integer.parseInt(request.getParameter("department_id"));
                String position = new String(request.getParameter("position").getBytes("ISO-8859-1"), "UTF-8");
                int userId = Integer.parseInt(request.getParameter("user_id"));
                updateEmployee(conn, id, name, departmentId, position, userId);
                response.sendRedirect("EmployeeServlet");
                return;
            } else if ("add".equals(action)) {
                String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
                int departmentId = Integer.parseInt(request.getParameter("department_id"));
                String position = new String(request.getParameter("position").getBytes("ISO-8859-1"), "UTF-8");
                int userId = Integer.parseInt(request.getParameter("user_id"));
                addEmployee(conn, name, departmentId, position, userId);
                response.sendRedirect("EmployeeServlet");
                return;
            }

            String search = request.getParameter("search");
            if (search != null && !search.isEmpty()) {
                searchEmployees(conn, request, search);
            } else {
                listEmployees(conn, request);
            }

            request.getRequestDispatcher("employee_management.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) { }
            try { if (stmt != null) stmt.close(); } catch (Exception e) { }
            try { if (conn != null) conn.close(); } catch (Exception e) { }
        }
    }

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

    private void deleteEmployee(Connection conn, int id) throws Exception {
        String sql = "DELETE FROM employee WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        }
    }

    private void updateEmployee(Connection conn, int id, String name, int departmentId, String position, int userId) throws Exception {
        String sql = "UPDATE employee SET name = ?, department_id = ?, position = ?, user_id = ? WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setInt(2, departmentId);
            pstmt.setString(3, position);
            pstmt.setInt(4, userId);
            pstmt.setInt(5, id);
            pstmt.executeUpdate();
        }
    }

    private void addEmployee(Connection conn, String name, int departmentId, String position, int userId) throws Exception {
        String sql = "INSERT INTO employee (name, department_id, position, user_id) VALUES (?, ?, ?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setInt(2, departmentId);
            pstmt.setString(3, position);
            pstmt.setInt(4, userId);
            pstmt.executeUpdate();
        }
    }

    private void listEmployees(Connection conn, HttpServletRequest request) throws Exception {
        Statement stmt = conn.createStatement();
        String sql = "SELECT * FROM employee";
        ResultSet rs = stmt.executeQuery(sql);

        StringBuilder employees = new StringBuilder();
        employees.append("<table border='1'>");
        employees.append("<tr><th>ID</th><th>Name</th><th>Department ID</th><th>Position</th><th>User ID</th><th>操作</th></tr>");

        while (rs.next()) {
            int id = rs.getInt("id");
            employees.append("<tr>");
            employees.append("<td>").append(id).append("</td>");
            employees.append("<td>").append(rs.getString("name")).append("</td>");
            employees.append("<td>").append(rs.getInt("department_id")).append("</td>");
            employees.append("<td>").append(rs.getString("position")).append("</td>");
            employees.append("<td>").append(rs.getInt("user_id")).append("</td>");
            employees.append("<td>")
                    .append("<button class='button' onclick=\"location.href='employee_edit.jsp?id=").append(id).append("&name=").append(rs.getString("name")).append("&department_id=").append(rs.getInt("department_id")).append("&position=").append(rs.getString("position")).append("&user_id=").append(rs.getInt("user_id")).append("'\">修改</button>")
                    .append("<button class='button' onclick=\"location.href='EmployeeServlet?action=delete&id=").append(id).append("'\">删除</button>")
                    .append("</td>");
            employees.append("</tr>");
        }
        employees.append("</table>");
        request.setAttribute("employees", employees.toString());
    }

    private void searchEmployees(Connection conn, HttpServletRequest request, String search) throws Exception {
        String sql = "SELECT * FROM employee WHERE id = ? OR name LIKE ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, search);
            pstmt.setString(2, "%" + search + "%");
            ResultSet rs = pstmt.executeQuery();

            StringBuilder employees = new StringBuilder();
            employees.append("<table border='1'>");
            employees.append("<tr><th>ID</th><th>Name</th><th>Department ID</th><th>Position</th><th>User ID</th><th>操作</th></tr>");

            while (rs.next()) {
                int id = rs.getInt("id");
                employees.append("<tr>");
                employees.append("<td>").append(id).append("</td>");
                employees.append("<td>").append(rs.getString("name")).append("</td>");
                employees.append("<td>").append(rs.getInt("department_id")).append("</td>");
                employees.append("<td>").append(rs.getString("position")).append("</td>");
                employees.append("<td>").append(rs.getInt("user_id")).append("</td>");
                employees.append("<td>")
                        .append("<button class='button' onclick=\"location.href='employee_edit.jsp?id=").append(id).append("&name=").append(rs.getString("name")).append("&department_id=").append(rs.getInt("department_id")).append("&position=").append(rs.getString("position")).append("&user_id=").append(rs.getInt("user_id")).append("'\">修改</button>")
                        .append("<button class='button' onclick=\"location.href='EmployeeServlet?action=delete&id=").append(id).append("'\">删除</button>")
                        .append("</td>");
                employees.append("</tr>");
            }
            employees.append("</table>");
            request.setAttribute("employees", employees.toString());
        }
    }
}

前端页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>员工管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: url('images/05.png') no-repeat center center fixed;
            background-size: cover;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0;
            padding: 0;
            height: 100vh;
        }
        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 80%;
            text-align: center;
        }
        h2 {
            margin-bottom: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .button {
            padding: 10px 20px;
            margin: 10px 5px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .button:hover {
            background-color: #0056b3;
        }
        form {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }
        form input[type="text"] {
            padding: 10px;
            margin-right: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            width: 200px;
        }
        .employee-list {
            margin-top: 20px;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>员工管理</h2>
    <div>
        <button class="button" onclick="location.href='employee_add.jsp'">添加员工</button>
        <button class="button" onclick="location.href='index.jsp'">返回</button>
    </div>
    <form method="get" action="EmployeeServlet">
        <input type="text" name="search" placeholder="输入员工ID或姓名查询">
        <button type="submit" class="button">查询</button>
    </form>
    <div id="employeeList" class="employee-list">
        ${employees} <!-- 显示从 EmployeeServlet 传递过来的员工数据 -->
    </div>
</div>
</body>
</html>

4.5 任务管理

后端实现:

package com.xxxx.Servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/TaskServlet")
public class TaskServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        Connection conn = JDBC.getConn();
        Statement stmt = null;
        ResultSet rs = null;

        try {
            String action = request.getParameter("action");
            if ("delete".equals(action)) {
                int id = Integer.parseInt(request.getParameter("id"));
                deleteTask(conn, id);
            } else if ("edit".equals(action)) {
                int id = Integer.parseInt(request.getParameter("id"));
                if (request.getParameter("title") != null) {
                    // Update task
                    String title = request.getParameter("title");
                    String description = request.getParameter("description");
                    int departmentId = Integer.parseInt(request.getParameter("department_id"));
                    int employeeId = Integer.parseInt(request.getParameter("employee_id"));
                    String status = request.getParameter("status");
                    updateTask(conn, id, title, description, departmentId, employeeId, status);
                    response.sendRedirect("TaskServlet");
                } else {
                    // Get task data for editing
                    String sql = "SELECT * FROM tasks WHERE id = ?";
                    try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                        pstmt.setInt(1, id);
                        rs = pstmt.executeQuery();
                        if (rs.next()) {
                            request.setAttribute("task", rs);
                            request.getRequestDispatcher("task_edit.jsp").forward(request, response);
                        }
                    }
                }
            } else if ("add".equals(action)) {
                String title = request.getParameter("title");
                String description = request.getParameter("description");
                int departmentId = Integer.parseInt(request.getParameter("department_id"));
                int employeeId = Integer.parseInt(request.getParameter("employee_id"));
                String status = request.getParameter("status");
                addTask(conn, title, description, departmentId, employeeId, status);
            }

            String search = request.getParameter("search");
            if (search != null && !search.trim().isEmpty()) {
                search = "%" + search.trim() + "%";
                String sql = "SELECT * FROM tasks WHERE title LIKE ? OR CAST(id AS CHAR) LIKE ?";
                try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                    pstmt.setString(1, search);
                    pstmt.setString(2, search);
                    rs = pstmt.executeQuery();
                }
            } else {
                stmt = conn.createStatement();
                String sql = "SELECT * FROM tasks";
                rs = stmt.executeQuery(sql);
            }

            StringBuilder tasks = new StringBuilder();
            tasks.append("<tr><th>ID</th><th>Title</th><th>Description</th><th>Department ID</th><th>Employee ID</th><th>Status</th><th>操作</th></tr>");

            while (rs.next()) {
                int id = rs.getInt("id");
                tasks.append("<tr>");
                tasks.append("<td>").append(id).append("</td>");
                tasks.append("<td>").append(rs.getString("title")).append("</td>");
                tasks.append("<td>").append(rs.getString("description")).append("</td>");
                tasks.append("<td>").append(rs.getInt("department_id")).append("</td>");
                tasks.append("<td>").append(rs.getInt("employee_id")).append("</td>");
                tasks.append("<td>").append(rs.getString("status")).append("</td>");
                tasks.append("<td>")
                        .append("<button class='button' onclick=\"location.href='TaskServlet?action=edit&id=").append(id).append("'\">修改</button>")
                        .append("<button class='button' onclick=\"location.href='TaskServlet?action=delete&id=").append(id).append("'\">删除</button>")
                        .append("</td>");
                tasks.append("</tr>");
            }
            request.setAttribute("tasks", tasks.toString());
            request.getRequestDispatcher("task_management.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) { }
            try { if (stmt != null) stmt.close(); } catch (Exception e) { }
            try { if (conn != null) conn.close(); } catch (Exception e) { }
        }
    }

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

    private void deleteTask(Connection conn, int id) throws Exception {
        String sql = "DELETE FROM tasks WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        }
    }

    private void updateTask(Connection conn, int id, String title, String description, int departmentId, int employeeId, String status) throws Exception {
        String sql = "UPDATE tasks SET title = ?, description = ?, department_id = ?, employee_id = ?, status = ? WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, title);
            pstmt.setString(2, description);
            pstmt.setInt(3, departmentId);
            pstmt.setInt(4, employeeId);
            pstmt.setString(5, status);
            pstmt.setInt(6, id);
            pstmt.executeUpdate();
        }
    }

    private void addTask(Connection conn, String title, String description, int departmentId, int employeeId, String status) throws Exception {
        String sql = "INSERT INTO tasks (title, description, department_id, employee_id, status) VALUES (?, ?, ?, ?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, title);
            pstmt.setString(2, description);
            pstmt.setInt(3, departmentId);
            pstmt.setInt(4, employeeId);
            pstmt.setString(5, status);
            pstmt.executeUpdate();
        }


    }
}

 前端页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>任务管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: url('images/05.png') no-repeat center center fixed;
            background-size: cover;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 80%;
            max-width: 800px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .button {
            padding: 8px 16px;
            margin: 5px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }
        .button:hover {
            background-color: #0056b3;
        }
        .search-container {
            margin-bottom: 20px;
        }
        .search-container input[type=text] {
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #ddd;
            width: 200px;
        }
        .search-container button {
            padding: 10px 20px;
            margin-left: 10px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .search-container button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>任务管理</h2>
    <button class="button" onclick="location.href='task_assign.jsp'">派发任务</button>
    <button class="button" onclick="location.href='index.jsp'">返回</button>
    <table>
        <tbody id="taskTableBody">
        ${tasks} <!-- 显示从 TaskServlet 传递过来的任务数据 -->
        </tbody>
    </table>
</div>
    <script>
        function searchTasks() {
            var input = document.getElementById("searchInput").value.toUpperCase();
            var rows = document.getElementById("taskTableBody").getElementsByTagName("tr");

            for (var i = 0; i < rows.length; i++) {
                var title = rows[i].getElementsByTagName("td")[1].textContent.toUpperCase();
                var description = rows[i].getElementsByTagName("td")[2].textContent.toUpperCase();

                if (title.indexOf(input) > -1 || description.indexOf(input) > -1) {
                    rows[i].style.display = "";
                } else {
                    rows[i].style.display = "none";
                }
            }
        }
    </script>
</body>
</html>

4.6 任务查看 

后端实现:

package com.xxxx.Servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

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

@WebServlet("/ViewTasksServlet")
public class ViewTasksServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            conn = JDBC.getConn();
            String sql = "SELECT * FROM task_assignment";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);

            StringBuilder tasks = new StringBuilder();
            tasks.append("<table border='1'>");
            tasks.append("<tr><th>ID</th><th>任务ID</th><th>员工ID</th><th>文件名</th><th>上传时间</th><th>审核</th><th>状态</th></tr>");

            while (rs.next()) {
                tasks.append("<tr>");
                tasks.append("<td>").append(rs.getInt("id")).append("</td>");
                tasks.append("<td>").append(rs.getInt("task_id")).append("</td>");
                tasks.append("<td>").append(rs.getInt("employee_id")).append("</td>");
                tasks.append("<td>").append(rs.getString("file_name")).append("</td>");
                tasks.append("<td>").append(rs.getTimestamp("uploaded_at")).append("</td>");
                tasks.append("<td><a href='ReviewTaskServlet?id=").append(rs.getInt("id")).append("'>审核</a></td>");
                tasks.append("<td>").append(rs.getString("status")).append("</td>");
                tasks.append("</tr>");
            }
            tasks.append("</table>");

            request.setAttribute("tasks", tasks.toString());
            request.getRequestDispatcher("view_tasks.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (stmt != null)
                    stmt.close();
                if (conn != null)
                    conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

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

 前端实现:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>任务查看</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: url('images/05.png') no-repeat center center fixed;
            background-size: cover;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .container {
            width: 80%;
            padding: 20px;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin-right: 10px;
            cursor: pointer;
            border-radius: 5px;
        }
        .button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>任务查看</h1>
    <div style="margin-bottom: 10px;">
        <button class="button" onclick="location.href='index.jsp'">返回</button>
        <button class="button" onclick="location.href='ExportPerformanceCSVServlet'">导出任务</button>
    </div>
    <table>
        <thead>
        <tr>
            <th>ID</th>
            <th>标题</th>
            <th>描述</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <%= request.getAttribute("tasks") %>
        </tbody>
    </table>
</div>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值