** 一、【项目简介】**
本项目是基于Tomcat+Servlet+MySql+JSP实现的学生宿舍管理系统,适合大一初学Java web的期末小项目,增删改查
- 开发工具:IDEA 2022.2
- 开发环境:JDK 1.8 + Tomcat 9.0.55 +MySql 8.0(Navicat)
二、【项目结构】
三、【前期准备】
- 新建数据库
- 输入数据库代码
DROP TABLE IF EXISTS `t_employee`;CREATE TABLE `t_employee` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `emp_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '员工姓名', `emp_gender` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '员工性别', `emp_dept` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '员工部门', `emp_salary` double DEFAULT NULL COMMENT '员工薪资', PRIMARY KEY (`id`) USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;INSERT INTO `t_employee` VALUES (1, '张三', '男', '软件部', 3000);INSERT INTO `t_employee` VALUES (2, '小辉', '男', '软件部', 2500);INSERT INTO `t_employee` VALUES (3, '王五', '女', '软件部', 3000);
- 配置JDK和Tomcat:
四、【前端代码】
- 登录页代码
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>登录</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { background: url('https://www.fjpit.edu.cn/_upload/article/images/85/0a/ace6605245f7aa03c4f70daef565/4859390e-bc87-42e1-896f-44386bc14740.png') no-repeat center center fixed; background-size: cover; height: 100vh; display: flex; justify-content: center; align-items: center; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } .login_box { text-align: center; width: 40%; background: rgba(255, 255, 255, 0.85); padding: 30px; border-radius: 10px; color: black; box-shadow: 0 0 20px rgba(0, 0, 0, 0.2); } .login_box h2 { margin-bottom: 20px; text-align: center; } input[type="text"], input[type="password"] { width: 60%; font-size: 20px; color: black; background: transparent; padding: 8px 10px; margin-top: 10px; border: none; border-bottom: 0.5px solid black; outline: none; } .button-box{ display: flex; justify-content: center; } button { margin-top: 20px; width: 60%; height: 40px; background-color: #0073e6; color: white; border: none; cursor: pointer; transition: background-color 0.3s; } button:hover { background-color: #005bb5; } .footer{ text-align: center; } .footer img{ margin-top: 20px; width: 200px; height: 35px; } </style></head><body><div class="login_box"> <h2>学生宿舍管理系统</h2> <form action="loginServlet" method="POST"> <div class="input_box"> 账号:<input type="text" name="account"><br> </div> <div class="input_box"> 密码:<input type="password" name="password"><br> </div> <div class="button-box"><button>登录</button></div> </form> <div class="footer"> 这里放置logo<img src="https://cas.paas.fjpit.cn/cas/file/png/logo.png?cas-server-site-ui__20240411__fe9a3bfc-24dc-42ef-8610-9ff46ac9a0d8__lQLPJyDFBuzsWEnM8M0F-rAunPjPBWF25gYEiP2J_fYA_1530_240.png"> </div></div></body></html>
- 主页代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>学生宿舍管理系统</title> <style> * { text-decoration: none; color: inherit; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; box-sizing: border-box; } body { background: url('https://www.fjpit.edu.cn/_upload/article/images/85/0a/ace6605245f7aa03c4f70daef565/4859390e-bc87-42e1-896f-44386bc14740.png') no-repeat center center fixed; background-size: cover; margin: 0; padding: 0; height: 100vh; display: flex; justify-content: center; align-items: center; background-blend-mode: overlay; } .main { width: 943px; height: 618px; background: rgba(255, 255, 255, 0.85); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); border-radius: 20px; overflow: hidden; display: flex; flex-direction: column; } .header { background: #0073e6; color: white; padding: 20px; display: flex; justify-content: space-between; align-items: center; border-top-left-radius: 20px; border-top-right-radius: 20px; } .header .title { font-size: 1.8em; font-weight: bold; } .header .user { font-size: 1.2em; } .content { padding: 30px; text-align: center; flex-grow: 1; } .content h2 { margin-top: 0; color: #0073e6; font-size: 3em; } .menu { margin: 20px 0; display: flex; justify-content: center; gap: 60px; } .menu a { background: #0073e6; color: white; padding: 20px 40px; border-radius: 10px; text-decoration: none; transition: background 0.3s, transform 0.3s; font-size: 1.2em; } .menu a:hover { background: #005bb5; transform: scale(1.1); } .search-box { margin: 20px auto; text-align: center; } .search-box input[type="text"] { width: 70%; padding: 15px; font-size: 1.1em; border: 2px solid #0073e6; border-radius: 10px; } .footer { background: #0073e6; color: white; padding: 20px; text-align: center; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; font-size: 1.1em; } .footer img { width: 270px; height: 50px; } </style></head><body><div class="main"> <div class="header"> <div class="title">福信学生宿舍管理系统</div> <div class="user">欢迎您,管理员 <a href="adminCenter.jsp">管理员中心</a></div> </div> <div class="content"> <h2>欢迎登录学生宿舍管理系统</h2> <div class="menu"> <a href="empList">宿舍信息</a> <a href="addEmp.html">添加宿舍</a> </div> <div class="search-box"> <input type="text" placeholder="请输入学生姓名 宿舍号"> </div> <p>请从上方菜单中选择您需要的操作</p> </div> <div class="footer"> 这里放置logo<img src="https://cas.paas.fjpit.cn/cas/file/png/logo.png?cas-server-site-ui__20240411__fe9a3bfc-24dc-42ef-8610-9ff46ac9a0d8__lQLPJyDFBuzsWEnM8M0F-rAunPjPBWF25gYEiP2J_fYA_1530_240.png"> </div></div></body></html>
- 信息列表代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>学生宿舍信息</title> <style> * { text-decoration: none; color: inherit; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; box-sizing: border-box; } body { background: url('https://www.fjpit.edu.cn/_upload/article/images/85/0a/ace6605245f7aa03c4f70daef565/4859390e-bc87-42e1-896f-44386bc14740.png') no-repeat center center fixed; background-size: cover; margin: 0; padding: 0; height: 100vh; display: flex; justify-content: center; align-items: center; background-blend-mode: overlay; } .main { width: 85%; max-width: 1400px; background: rgba(255, 255, 255, 0.85); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); border-radius: 20px; overflow: hidden; display: flex; flex-direction: column; } .header, .footer { background: #0073e6; color: white; padding: 20px; display: flex; justify-content: space-between; align-items: center; } .header { border-top-left-radius: 20px; border-top-right-radius: 20px; } .footer { background: #0073e6; color: white; padding: 20px; text-align: center; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; font-size: 1.1em; justify-content: center; } .footer img{ width: 270px; height: 50px; } .header a, .footer a { color: white; margin-left: 30px; font-weight: bold; } .content { width: 969px; height: 445px; margin: 0 auto; padding: 20px; text-align: center; flex-grow: 1; display: flex; flex-direction: column; justify-content: center; } .content h2 { margin-bottom: 5px; color: #0073e6; font-size: 2.5em; } .menu { margin: 20px 0; display: flex; justify-content: space-between; } .menu a { background: #0073e6; color: white; padding: 10px 20px; border-radius: 10px; text-decoration: none; transition: background 0.3s, transform 0.3s; font-size: 1em; } .menu a:hover { background: #005bb5; transform: scale(1.05); } .two { margin: 20px 0; } .two th, .two td { border: 1px solid #0073e6; padding: 10px; } .two table { width: 100%; border-collapse: collapse; } .two table thead { background: #0073e6; color: white; } .page-nav { margin: 20px 0; display: flex; justify-content: center; } .page-nav a { margin: 0 10px; color: #0073e6; text-decoration: none; } .page-nav a.pageActive { color: black; margin-bottom: 5px; } </style></head><body><div class="main"> <div class="header"> <p>欢迎您,管理员</p> </div> <div class="content"> <h2>学生宿舍列表</h2> <div class="menu"> <a href="main.jsp">返回系统</a> <a href="addEmp.html">添加宿舍</a> </div> <div class="two"> <table> <thead> <tr> <th>编号</th> <th>宿舍号</th> <th>是否满员</th> <th>楼层</th> <th>人数</th> <th>操作</th> </tr> </thead> <tbody> <c:forEach var="employee" items="${requestScope.pageDTO.date}"> <tr> <td>${employee.id}</td> <td>${employee.empName}</td> <td>${employee.empGender}</td> <td>${employee.empDept}</td> <td>${employee.empSalary}</td> <td><a href="findById?id=${employee.id}">修改</a> <a href="delEmp?id=${employee.id}">删除</a></td> </tr> </c:forEach> </tbody> </table> </div> <div class="page-nav"> <c:if test="${pageDTO.pageNumber>1}"> <a href="empList?pageNumber=${pageDTO.pageNumber -1}">上一页</a> </c:if> <c:forEach var="i" begin="1" end="${pageDTO.totalPage}"> <a href="empList?pageNumber=${i}" class="${i == pageDTO.pageNumber ? 'pageActive' : ''}">${i}</a> </c:forEach> <c:if test="${pageDTO.pageNumber < pageDTO.totalPage}"> <a href="empList?pageNumber=${pageDTO.pageNumber+1}">下一页</a> </c:if> </div> </div> <div class="footer"> 这里放置logo<img src="https://cas.paas.fjpit.cn/cas/file/png/logo.png?cas-server-site-ui__20240411__fe9a3bfc-24dc-42ef-8610-9ff46ac9a0d8__lQLPJyDFBuzsWEnM8M0F-rAunPjPBWF25gYEiP2J_fYA_1530_240.png"> </div></div></body></html>
- 修改和添加页代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html lang="en"><head> <meta charset="UTF-8"> <title>学生宿舍信息</title> <style> * { text-decoration: none; color: inherit; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; box-sizing: border-box; } body { background: url('https://www.fjpit.edu.cn/_upload/article/images/85/0a/ace6605245f7aa03c4f70daef565/4859390e-bc87-42e1-896f-44386bc14740.png') no-repeat center center fixed; background-size: cover; margin: 0; padding: 0; height: 100vh; display: flex; justify-content: center; align-items: center; background-blend-mode: overlay; } .main { width: 85%; max-width: 1400px; background: rgba(255, 255, 255, 0.85); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); border-radius: 20px; overflow: hidden; display: flex; flex-direction: column; } .header, .footer { background: #0073e6; color: white; padding: 20px; display: flex; justify-content: space-between; align-items: center; } .header { border-top-left-radius: 20px; border-top-right-radius: 20px; } .footer { background: #0073e6; color: white; padding: 20px; text-align: center; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; font-size: 1.1em; justify-content: center; } .footer img{ width: 270px; height: 50px; } .header a, .footer a { color: white; margin-left: 30px; font-weight: bold; } .content { width: 969px; height: 445px; margin: 0 auto; padding: 20px; text-align: center; flex-grow: 1; display: flex; flex-direction: column; justify-content: center; } .content h2 { margin-top: 50px; color: #0073e6; font-size: 2.5em; } .menu { display: flex; justify-content: center; } .menu a { background: #0073e6; color: white; padding: 10px 20px; border-radius: 10px; text-decoration: none; transition: background 0.3s, transform 0.3s; font-size: 1em; margin: 0 10px 0 10px; } .menu a:hover { background: #005bb5; transform: scale(1.05); } .search-box { margin: 20px auto; text-align: center; } .search-box input[type="text"] { width: 60%; padding: 10px; font-size: 1em; border: 2px solid #0073e6; border-radius: 10px; } .form-container { margin: 10px 0; display: flex; flex-direction: column; align-items: center; } .form-container form { width: 50%; background: #f7f7f7; border-radius: 10px; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); } .form-container form input[type="text"], .form-container form input[type="radio"], .form-container form button { margin: 10px 0; padding: 10px; font-size: 1em; } .form-container form button { width: 100px; border: none; border-radius: 6px; cursor: pointer; } .form-container .add { background: #005bb5; color: white; } .form-container .new { background: #005bb5; color: white; } </style></head><body><div class="main"> <div class="header"> <p>欢迎您,管理员</p> </div> <div class="content"> <h2>修改宿舍信息</h2> <div class="menu"> <a href="main.jsp">返回系统</a> <a href="empList">宿舍列表</a> </div> <div class="form-container"> <form action="updateEmp" method="post"> <input type="hidden" name="id" value="${employee.id}"> 宿舍:<input name="empName" value="${employee.empName}" type="text" /><br /> 是否满员: <c:choose> <c:when test="${employee.empGender == '是'}"> <label><input name="empGender" type="radio" value="是" checked/>是</label> </c:when> <c:otherwise> <label><input name="empGender" type="radio" value="是">是</label> </c:otherwise> </c:choose> <c:choose> <c:when test="${employee.empGender == '否'}"> <label><input type="radio" name="empGender" value="否" checked/>否</label><br /> </c:when> <c:otherwise> <label><input type="radio" name="empGender" value="否">否</label><br /> </c:otherwise> </c:choose> 人数:<input value="${ employee.empSalary}" name="empSalary" type="text" /><br> <button class="add">修改</button> <button class="new" type="reset">重置</button> </form> </div> </div> <div class="footer"> 这里放置logo<img src="https://cas.paas.fjpit.cn/cas/file/png/logo.png?cas-server-site-ui__20240411__fe9a3bfc-24dc-42ef-8610-9ff46ac9a0d8__lQLPJyDFBuzsWEnM8M0F-rAunPjPBWF25gYEiP2J_fYA_1530_240.png"> </div></div></body></html>``````<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>添加宿舍信息</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } body { background: url('https://www.fjpit.edu.cn/_upload/article/images/85/0a/ace6605245f7aa03c4f70daef565/4859390e-bc87-42e1-896f-44386bc14740.png') no-repeat center center fixed; background-size: cover; height: 100vh; display: flex; justify-content: center; align-items: center; } .main { width: 600px; background: rgba(255, 255, 255, 0.95); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2); border-radius: 20px; padding: 20px; } .header, .footer { background: #0073e6; color: white; padding: 10px 20px; border-radius: 10px 10px 0 0; text-align: center; } .header a, .footer a { color: white; text-decoration: none; margin: 0 10px; font-weight: bold; } .content { padding: 20px; text-align: center; } .content h2 { margin-top: 0; color: #0073e6; font-size: 1.8em; } .content form { flex-direction: column; text-align: center; } .content form input[type="text"], .content form input[type="radio"] { margin: 10px 0; padding: 10px; width: 300px; border: 1px solid #0073e6; border-radius: 5px; font-size: 1em; } .content form label { font-size: 1em; color: #0073e6; } .content form button { margin-top: 20px; background: #0073e6; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; transition: background 0.3s; font-size: 1em; } .content form button:hover { background: #005bb5; } .footer { background: #0073e6; color: white; border-radius: 0 0 20px 20px; text-align: center; } .footer img{ width: 180px; height: 30px; } </style></head><body><div class="main"> <div class="header"> <a href="empList">宿舍信息</a> <a href="main.jsp">返回系统</a> </div> <div class="content"> <h2>添加宿舍信息</h2> <form action="saveEmp" method="post"> <div> 名称:<input name="empName" type="text" /><br /> </div> <div> 是否空置:<label><input name="empGender" type="radio" value="是">是</label> <label><input type="radio" name="empGender" value="否">否</label><br /> </div> <div> 宿舍类型:<input name="empDept" type="text" /><br /> </div> <div> 费用:<input name="empSalary" type="text" /><br> </div> <div> <button type="submit" >添加</button> <button type="reset">重置</button> </div> </form> </div> <div class="footer"> 这里放置logo<img src="https://cas.paas.fjpit.cn/cas/file/png/logo.png?cas-server-site-ui__20240411__fe9a3bfc-24dc-42ef-8610-9ff46ac9a0d8__lQLPJyDFBuzsWEnM8M0F-rAunPjPBWF25gYEiP2J_fYA_1530_240.png"> </div></div></body></html>
- 修改和添加反馈代码
<%-- Created by IntelliJ IDEA. User: 86177 Date: 2024/5/24 Time: 14:38 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>消息提示</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } body { background: url('https://www.fjpit.edu.cn/_upload/article/images/85/0a/ace6605245f7aa03c4f70daef565/4859390e-bc87-42e1-896f-44386bc14740.png') no-repeat center center fixed; background-size: cover; height: 100vh; display: flex; justify-content: center; align-items: center; } .main { width: 600px; background: rgba(255, 255, 255, 0.95); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2); border-radius: 20px; padding: 20px; text-align: center; } .header, .footer { background: #0073e6; color: white; padding: 10px 20px; border-radius: 10px 10px 0 0; } .header a, .footer a { color: white; text-decoration: none; margin: 0 10px; font-weight: bold; } .content { padding: 20px; color: #0073e6; font-size: 1.2em; } .footer { background: #0073e6; color: white; border-radius: 0 0 20px 20px; text-align: center; } .footer img{ width: 180px; height: 30px; } .back-link { display: inline-block; margin-top: 20px; padding: 10px 20px; background: #0073e6; color: white; border-radius: 5px; text-decoration: none; transition: background 0.3s; } .back-link:hover { background: #005bb5; } </style></head><body><div class="main"> <div class="header"> <a href="empList">宿舍信息</a> <a href="addEmp.html">添加宿舍</a> </div> <div class="content"> ${requestScope.msg} <br> <a href="empList" class="back-link">返回</a> </div> <div class="footer"> 这里放置logo<img src="https://cas.paas.fjpit.cn/cas/file/png/logo.png?cas-server-site-ui__20240411__fe9a3bfc-24dc-42ef-8610-9ff46ac9a0d8__lQLPJyDFBuzsWEnM8M0F-rAunPjPBWF25gYEiP2J_fYA_1530_240.png"> </div></div></body></html>
- 个人中心代码
<%-- Created by IntelliJ IDEA. User: c Date: 2024/6/26 Time: 16:11 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>管理员中心</title> <style> * { text-decoration: none; color: inherit; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; box-sizing: border-box; } body { background: url('https://www.fjpit.edu.cn/_upload/article/images/85/0a/ace6605245f7aa03c4f70daef565/4859390e-bc87-42e1-896f-44386bc14740.png') no-repeat center center fixed; background-size: cover; margin: 0; padding: 0; height: 100vh; display: flex; justify-content: center; align-items: center; background-blend-mode: overlay; } .main { width: 943px; height: 618px; background: rgba(255, 255, 255, 0.85); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); border-radius: 20px; overflow: hidden; display: flex; flex-direction: column; } .header { background: #0073e6; color: white; padding: 20px; display: flex; justify-content: space-between; align-items: center; border-top-left-radius: 20px; border-top-right-radius: 20px; } .header .title { font-size: 1.8em; font-weight: bold; } .header .user { font-size: 1.2em; } .content { padding: 30px; text-align: center; flex-grow: 1; } .content h2 { margin-top: 0; color: #0073e6; font-size: 3em; } .menu { margin: 20px 0; display: flex; justify-content: center; gap: 60px; } .menu a { background: #0073e6; color: white; padding: 20px 40px; border-radius: 10px; text-decoration: none; transition: background 0.3s, transform 0.3s; font-size: 1.2em; } .menu a:hover { background: #005bb5; transform: scale(1.1); } .footer { background: #0073e6; color: white; padding: 20px; text-align: center; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; font-size: 1.1em; } .footer img { width: 270px; height: 50px; } </style></head><body><div class="main"> <div class="header"> <div class="title">管理员中心</div> <div class="user">欢迎您,管理员</div> </div> <div class="content"> <h2>管理员操作菜单</h2> <div class="menu"> <a href="empList">查看宿舍信息</a> <a href="main.jsp">返回系统主页</a> <a href="login.html">退出系统登录</a> </div> </div> <div class="footer"> 这里放置logo<img src="https://cas.paas.fjpit.cn/cas/file/png/logo.png?cas-server-site-ui__20240411__fe9a3bfc-24dc-42ef-8610-9ff46ac9a0d8__lQLPJyDFBuzsWEnM8M0F-rAunPjPBWF25gYEiP2J_fYA_1530_240.png"> </div></div></body></html>
五、【后端代码实现】
- 登录处理器实现
package com.servlet;import cn.hutool.crypto.digest.MD5;import com.dao.StudentDao;import com.model.Student;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 javax.servlet.http.HttpSession;import java.io.IOException;@WebServlet("/loginServlet")public class LoginServlet extends HttpServlet { private StudentDao studentDao = new StudentDao(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String account = req.getParameter("account"); Student student = studentDao.selectByAccount(account); if (student == null){ resp.getWriter().println("账号出错"); resp.getWriter().close(); return; } String stuPassword = student.getStuPassword(); String password = req.getParameter("password"); if (!stuPassword.equals(MD5.create().digestHex16(password))){ resp.getWriter().println("密码错误"); resp.getWriter().close(); return; } HttpSession session = req.getSession(); session.setAttribute("username",student.getStuName()); resp.sendRedirect("main.jsp"); }}
- 宿舍增删改实现
package com.servlet;import com.dao.EmployeeDao;import com.model.Employee;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 java.io.IOException;@WebServlet("/saveEmp")public class EmpSaveServlet extends HttpServlet { private EmployeeDao employeeDao= new EmployeeDao(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String name = req.getParameter("empName"); String gender = req.getParameter("empGender"); String salary = req.getParameter("empSalary"); int row = employeeDao.insert(new Employee(null, name, gender, null, Double.parseDouble(salary))); if (row > 0) { req.setAttribute("msg", "宿舍添加成功"); } else { req.setAttribute("msg", "宿舍添加失败"); } req.getRequestDispatcher("msg.jsp").forward(req, resp); }}``````package com.servlet;import com.dao.EmployeeDao;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 java.io.IOException;@WebServlet("/delEmp")public class EmpDelServlet extends HttpServlet { private EmployeeDao employeeDao = new EmployeeDao(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id"); int row = employeeDao.delete(Integer.parseInt(id)); if (row>0){ req.setAttribute("msg","宿舍删除成功"); }else{ req.setAttribute("msg","宿舍删除失败"); } req.getRequestDispatcher("msg.jsp").forward(req,resp); }}``````package com.servlet;import com.dao.EmployeeDao;import com.model.Employee;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 java.io.IOException;@WebServlet("/updateEmp")public class EmpUpdateServlet extends HttpServlet { private EmployeeDao employeeDao = new EmployeeDao(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String id = req.getParameter("id"); String name = req.getParameter("empName"); String gender = req.getParameter("empGender"); String salary = req.getParameter("empSalary"); Employee employee = new Employee(Integer.parseInt(id), name, gender, "1", Double.parseDouble(salary)); int rows = employeeDao.updateById(employee); if (rows > 0) { req.setAttribute("msg", "宿舍修改成功"); } else { req.setAttribute("msg", "宿舍修改失败"); } req.getRequestDispatcher("msg.jsp").forward(req, resp); }}
- 分页列表实现
package com.servlet;import com.dao.EmployeeDao;import com.model.Employee;import com.dto.PageDTO;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 java.io.IOException;@WebServlet("/empList")public class EmpListServlet extends HttpServlet { private EmployeeDao employeeDao = new EmployeeDao(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pageNumberStr = req.getParameter("pageNumber"); String pageLimitStr = req.getParameter("pageLimit"); int pageNumber = 1; int pageLimit = 5; if (pageNumberStr!=null){ pageNumber = Integer.parseInt(pageNumberStr); } if (pageLimitStr!=null){ pageLimit = Integer.parseInt(pageLimitStr); } PageDTO<Employee> pageDTO = employeeDao.selectList(pageNumber, pageLimit); req.setAttribute("pageDTO", pageDTO); req.getRequestDispatcher("EmpList.jsp").forward(req, resp); }}
- 数据库实现:需要根据电脑配置的Mysql,自行修改数据库用户名和密码
package com.servlet;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;public class Main { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.cj.jdbc.Driver"); String url ="jdbc:mysql://localhost:3306/web"; // String user ="root"; String password ="123456"; Connection connection=DriverManager.getConnection(url,user,password); String sql = "insert into t_student(stu_name,stu_gender,stu_birthday,stu_account,stu_password) values('小明','男','2000-12-13','xiaoming','123456')"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); System.out.println(connection); }}
- PageDTO
package com.dto;import java.util.List;public class PageDTO<T> { private int pageNumber; private int pageLimit; private int totalPage; private int totalCount; private List<T> date; public PageDTO() { } public PageDTO(int pageNumber, int pageLimit, int totalPage, int totalCount, List<T> date) { this.pageNumber = pageNumber; this.pageLimit = pageLimit; this.totalPage = totalPage; this.totalCount = totalCount; this.date = date; } @Override public String toString() { return "PageDTO{" + "pageNumber=" + pageNumber + ", pageLimit=" + pageLimit + ", totalPage=" + totalPage + ", totalCount=" + totalCount + ", date=" + date + '}'; } public int getPageNumber() { return pageNumber; } public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } public int getPageLimit() { return pageLimit; } public void setPageLimit(int pageLimit) { this.pageLimit = pageLimit; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public List<T> getDate() { return date; } public void setDate(List<T> date) { this.date = date; }}
- 数据库交互
package com.dao;import com.utils.DBUtils;import com.dto.PageDTO;import com.model.Employee;import java.sql.*;import java.util.ArrayList;public class EmployeeDao {public int selectCount(){ try { Connection connection = DBUtils.getConnection(); String sql = "select count(*) totalCount from t_employee"; PreparedStatement preparedStatement = connection.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { return resultSet.getInt("totalCount"); } return 0; } catch (SQLException e) { throw new RuntimeException(e); }} public PageDTO<Employee> selectList(int pageNumber , int pageLimit){ int totalCount = selectCount(); int totalPage = totalCount / pageLimit; if (totalCount % pageLimit >0){ totalPage++; } try { Connection connection = DBUtils.getConnection(); int offset = (pageNumber - 1) *pageLimit; String sql = "select * from t_employee limit ?,?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1,offset); preparedStatement.setInt(2,pageLimit); ResultSet resultSet = preparedStatement.executeQuery(); ArrayList<Employee> employees = new ArrayList<>(); while(resultSet.next()){ int id = resultSet.getInt("id"); String empName = resultSet.getString("emp_name"); String empGender = resultSet.getString("emp_gender"); String empDept = resultSet.getString("emp_dept"); double empSalary = resultSet.getDouble("emp_salary"); Employee employee = new Employee(id, empName, empGender, empDept, empSalary); employees.add(employee); } PageDTO<Employee> pageDTO = new PageDTO<>(pageNumber, pageLimit, totalPage, totalCount, employees); return pageDTO; } catch (SQLException e) { throw new RuntimeException(e); } } public int delete( Integer id){ return DBUtils.executeUpdate("delete from t_employee where id = ?",id); } public int insert(Employee employee){ return DBUtils.executeUpdate("insert into t_employee(emp_name,emp_gender,emp_dept,emp_salary)values(?,?,1,?)", employee.getEmpName(), employee.getEmpGender(), employee.getEmpSalary()); } public Employee selectById(int selectId){ try { Connection connection = DBUtils.getConnection(); String sql = "select * from t_employee where id = ?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1,selectId); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()){ int id = resultSet.getInt("id"); String empName = resultSet.getString("emp_name"); String empGender = resultSet.getString("emp_gender"); String empDept = resultSet.getString("emp_dept"); double empSalary = resultSet.getDouble("emp_salary"); Employee employee = new Employee(id, empName, empGender, empDept, empSalary); return employee; } return null; } catch (SQLException e) { throw new RuntimeException(e); } } public int updateById(Employee employee){ return DBUtils.executeUpdate("update t_employee set emp_name=?,emp_gender=?," + "emp_dept=?,emp_salary=? where id=?",employee.getEmpName(),employee.getEmpGender(), employee.getEmpDept(),employee.getEmpSalary(),employee.getId()); }}``````package com.dao;import com.model.Student;import com.utils.DBUtils;import java.sql.*;public class StudentDao { // selectByAccount() public Student selectByAccount(String account){ try { Connection connection = DBUtils.getConnection(); String sql = "select * from t_student where stu_account = ?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1,account); ResultSet resultSet = preparedStatement.executeQuery(); // while ? if (resultSet.next()){ int id = resultSet.getInt("id"); String stuName = resultSet.getString("stu_name"); String stuGender = resultSet.getString("stu_gender"); Date stuBirther = resultSet.getDate("stu_birthday"); String styAccount = resultSet.getString("stu_account"); String stuPassword = resultSet.getString("stu_password"); Student student = new Student(id, stuName, stuGender, stuBirther, styAccount, stuPassword); return student; }else{ return null; } } catch (SQLException e) { throw new RuntimeException(e); } } public int insert(Student student){ return DBUtils.executeUpdate("insert into t_student(stu_name,stu_gender,stu_birthday,stu_account,stu_password) values(?,?,?,?,?)", student.getStuName(), student.getStuGender(), student.getStuBirthday(), student.getStuAccount(), student.getStuPassword() ); }}
- 数据库连接
package com.utils;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;public class DBUtils { private static final String URL = "jdbc:mysql://localhost:3306/web"; private static final String USER = "root"; private static final String PASSWORD = "123456"; public static Connection getConnection(){ try { Class.forName("com.mysql.cj.jdbc.Driver"); return DriverManager.getConnection(URL, USER, PASSWORD); } catch (ClassNotFoundException | SQLException e) { throw new RuntimeException(e); } } public static int executeUpdate(String sql,Object ...params){ try { Connection connection = DBUtils.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { preparedStatement.setObject(i+1,params[i]); } return preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } }}
- 时间信息实现
package com.test;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class StringToDateTest { public static void main(String[] args) throws ParseException { String dateStr = "2024-05-17"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date parse = simpleDateFormat.parse(dateStr); System.out.println(parse); }}package com.test;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class StringToDateTest { public static void main(String[] args) throws ParseException { String dateStr = "2024-05-17"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date parse = simpleDateFormat.parse(dateStr); System.out.println(parse); }}
六、【部分效果展示】
七、【源代码下载】
本文转载自: https://blog.csdn.net/2301_81030220/article/details/139996409
版权归原作者 Mustrack 所有, 如有侵权,请联系我们删除。
版权归原作者 Mustrack 所有, 如有侵权,请联系我们删除。