Spring Boot学习随笔- JSP小项目-员工管理系统(验证码生成、增删改查) ...

打印 上一主题 下一主题

主题 985|帖子 985|积分 2955

学习视频:【编程不良人】2021年SpringBoot最新最全教程
第十章、项目开发

实现一个登录注册,增删改查功能的系统
10.1 项目开发流程


  • 需求分析
    分析用户主要需求 提取项目核心功能,根据核心功能构建页面原型
  • 库表设计:

    • 分析系统有哪些表
    • 分析表之间关联关系
    • 确定字段

  • 详细设计(流程图、伪代码):
    验证库表准确性
  • 功能实现(编码)
    环境搭建,具体功能实现
  • 功能测试,部署,上线,运维,维护
全栈式开发:前端+后端+运维
10.2 需求分析


  • 系统有哪些模块?
  • 每个模块功能有哪些?

    • 用户模块:登录、注册、验证码生成
    • 员工模块:查询、删除、更新、添加

10.3 库表设计

用户表:user
员工表:employee
表与表关系:user,employee 独立两张表
创建库表
  1. create database ems;
  2. use ems;
  3. create TABLE user(
  4. id int auto_increment  ,username VARCHAR(40) COMMENT '用户名' ,
  5. realname VARCHAR(40) COMMENT '真实姓名' ,
  6. `password` VARCHAR(50) COMMENT '密码',gender TINYINT(3) COMMENT '性别',
  7. PRIMARY KEY (`id`)
  8. );
  9. create TABLE employee(
  10. id int auto_increment,
  11. name VARCHAR(40) COMMENT '姓名',
  12. birthday datetime COMMENT '生日',
  13. salary DOUBLE COMMENT '薪资',
  14. gender TINYINT(3) COMMENT '性别',
  15. PRIMARY KEY(id)
  16. )
复制代码
10.5 编码环节

技术选型:SpringBoot + MyBatis + JSP + MySQL
环境搭建:Spring Boot + JSP + MyBatis
创建名为ems-jsp的项目,并引入web支持依赖,创建完成

环境搭建

pom.xml依赖导入
  1. <dependencies>
  2.     <dependency>
  3.         <groupId>org.springframework.boot</groupId>
  4.         <artifactId>spring-boot-starter-web</artifactId>
  5.     </dependency>
  6.     <dependency>
  7.         <groupId>org.springframework.boot</groupId>
  8.         <artifactId>spring-boot-starter-test</artifactId>
  9.         <scope>test</scope>
  10.     </dependency>
  11.    
  12.     <dependency>
  13.         <groupId>org.apache.tomcat.embed</groupId>
  14.         <artifactId>tomcat-embed-jasper</artifactId>
  15.     </dependency>
  16.    
  17.    
  18.     <dependency>
  19.         <groupId>com.alibaba</groupId>
  20.         <artifactId>druid</artifactId>
  21.         <version>1.1.19</version>
  22.     </dependency>
  23.    
  24.     <dependency>
  25.         <groupId>mysql</groupId>
  26.         <artifactId>mysql-connector-java</artifactId>
  27.     </dependency>
  28.    
  29.     <dependency>
  30.         <groupId>org.mybatis.spring.boot</groupId>
  31.         <artifactId>mybatis-spring-boot-starter</artifactId>
  32.         <version>3.0.0</version>
  33.     </dependency>
  34.    
  35.     <dependency>
  36.         <groupId>org.springframework.boot</groupId>
  37.         <artifactId>spring-boot-devtools</artifactId>
  38.     </dependency>
  39. </dependencies>
复制代码
application.yml:
  1. # 应用服务 WEB 访问端口
  2. server:
  3.   port: 8989
  4.   servlet:
  5.     context-path: /ems-jsp
  6.     jsp:
  7.       init-parameters:
  8.         development: true # 开启jsp模板开发模式
  9. # 配置jsp展示
  10. spring:
  11.   mvc:
  12.     view:
  13.       prefix: /
  14.       suffix: .jsp
  15.   datasource:
  16.     type: com.alibaba.druid.pool.DruidDataSource
  17.     driver-class-name: com.mysql.cj.jdbc.Driver
  18.     url: jdbc:mysql://localhost:3306/ems?characterEncoding=UTF-8
  19.     username: root
  20.     password: 123456
  21. # 配置mybatis
  22. mybatis:
  23.   mapper-locations: classpath:com.baizhi/mapper/*.xml
  24.   type-aliases-package: com.baizhi.entity
  25. # 配置日志
  26. logging:
  27.   level:
  28.     com.baizhi: debug
复制代码
添加dao包扫描
  1. @SpringBootApplication
  2. @MapperScan("com.baizhi.dao")
  3. public class EmsJspApplication {
  4.     public static void main(String[] args) {
  5.         SpringApplication.run(EmsJspApplication.class, args);
  6.     }
  7. }
复制代码
10.6 验证码实现


  • 业务逻辑

    • 生成随机字符(依靠工具类VerifyCode)
    • 放入session(与前端传过来的验证码进行比对),放进map(传给前端)
    • 生成图片响应

  • register.jsp
    1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    2. <!DOCTYPE html>
    3. <html>
    4. <head>
    5.     <meta charset="UTF-8">
    6.     <title>Registration Page</title>
    7.     <link rel="stylesheet" type="text/css" href="css/register.css">
    8. </head>
    9. <body>
    10. <h2>用户注册</h2>
    11.     <h3 >${param.msg}</h3>
    12.     <form action="${pageContext.request.contextPath}/user/register" method="post">
    13.         用户名: <input type="text"  name="username"><br>
    14.         真实姓名: <input type="text" name="realname" ><br>
    15.         密码: <input type="password" name="password" ><br>
    16. <%--        确认密码: <input type="password" name="confirmPassword"><br>--%>
    17.         性别:
    18.         <select name="gender" >
    19.             <option value="1">男</option>
    20.             <option value="0">女</option>
    21.         </select><br>
    22.         
    23.         <label for="verifyCode">验证码:</label><br>
    24.         <img id="verifyCode" src="" alt="Captcha Image">
    25.         <a target="_blank" href="https://www.cnblogs.com/javascript:" id="refresh">换一张</a>
    26.         <input type="text"  name="code"><br>
    27.         <input type="submit" value="注册">
    28.     </form>
    29. </body>
    30. </html>
    复制代码
  • css
    1. body {
    2.     font-family: 'Arial', sans-serif;
    3.     margin: auto;
    4.     justify-content: center;
    5.     align-items: center;
    6.     width: 500px;
    7.     height: 800px;
    8.     /*border: 1px solid red;*/
    9. }
    10. .container {
    11.     padding: 30px;
    12.     background-color: #ffffff;
    13.     border-radius: 8px;
    14.     box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
    15.     /*border: 1px solid red;*/
    16. }
    17. h2 {
    18.     text-align: center;
    19. }
    20. input[type="text"],
    21. input[type="password"],
    22. input[type="submit"],
    23. select {
    24.     width: calc(100% - 20px);
    25.     margin-bottom: 15px;
    26.     padding: 10px;
    27.     border: 1px solid #dddddd;
    28.     border-radius: 5px;
    29.     transition: border-color 0.3s ease-in-out;
    30. }
    31. input[type="text"]:focus,
    32. input[type="password"]:focus,
    33. select:focus {
    34.     outline: none;
    35.     border-color: #66afe9;
    36. }
    37. input[type="submit"] {
    38.     background-color: #4CAF50;
    39.     color: white;
    40.     border: none;
    41.     cursor: pointer;
    42.     transition: background-color 0.3s ease-in-out;
    43. }
    44. input[type="submit"]:hover {
    45.     background-color: seagreen;
    46. }
    复制代码
  • 验证码 实现类
    1. package com.baizhi.utils;
    2. import javax.imageio.ImageIO;
    3. import java.awt.Color;
    4. import java.awt.Font;
    5. import java.awt.Graphics;
    6. import java.awt.image.BufferedImage;
    7. import java.io.FileOutputStream;
    8. import java.io.IOException;
    9. import java.io.OutputStream;
    10. import java.util.Random;
    11. public class VerifyCode {
    12.     private int width = 100;// 定义图片的width
    13.     private int height = 40;// 定义图片的height
    14.     private int codeCount = 4;// 定义图片上显示验证码的个数
    15.     private int lineCount = 20;// 定义图片上显示干扰线的条数
    16.     private String code = null;// 定义用于保存验证码的字符串
    17.     private BufferedImage buffImg = null;// 定义图片Buffer
    18.     private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
    19.             'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    20.     public VerifyCode() {
    21.         this.createCode();
    22.     }
    23.     /**
    24.      * @param width
    25.      *            图片宽
    26.      * @param height
    27.      *            图片高
    28.      */
    29.     public VerifyCode(int width, int height) {
    30.         this.width = width;
    31.         this.height = height;
    32.         this.createCode();
    33.     }
    34.     /**
    35.      * @param width
    36.      *            图片宽
    37.      * @param height
    38.      *            图片高
    39.      * @param codeCount
    40.      *            字符个数
    41.      * @param lineCount
    42.      *            干扰线条数
    43.      */
    44.     public VerifyCode(int width, int height, int codeCount, int lineCount) {
    45.         this.width = width;
    46.         this.height = height;
    47.         this.codeCount = codeCount;
    48.         this.lineCount = lineCount;
    49.         this.createCode();
    50.     }
    51.     public void createCode() {
    52.         int x = 0, fontHeight = 0, codeY = 0;
    53.         int red = 0, green = 0, blue = 0;
    54.         x = width / (codeCount + 2);// 每个字符的宽度
    55.         fontHeight = height - 2;// 字体的高度
    56.         codeY = height - 4;
    57.         // 图像buffer
    58.         buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    59.         Graphics g = buffImg.createGraphics();
    60.         // 创建一个随机数生成器类
    61.         Random random = new Random();
    62.         // 将图像填充为白色
    63.         g.setColor(Color.WHITE);
    64.         g.fillRect(0, 0, width, height);
    65.         // 创建字体,字体的大小应该根据图片的高度来定。
    66.         Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
    67.         // 设置字体。
    68.         g.setFont(font);
    69.         for (int i = 0; i < lineCount; i++) {
    70.             // 设置随机开始和结束坐标
    71.             int xs = random.nextInt(width);// x坐标开始
    72.             int ys = random.nextInt(height);// y坐标开始
    73.             int xe = xs + random.nextInt(width / 8);// x坐标结束
    74.             int ye = ys + random.nextInt(height / 8);// y坐标结束
    75.             // 生成随机颜色
    76.             red = random.nextInt(255);
    77.             green = random.nextInt(255);
    78.             blue = random.nextInt(255);
    79.             g.setColor(new Color(red, green, blue));
    80.             g.drawLine(xs, ys, xe, ye);
    81.         }
    82.         // randomCode记录随机产生的验证码
    83.         StringBuffer randomCode = new StringBuffer();
    84.         // 随机产生codeCount个字符的验证码。
    85.         for (int i = 0; i < codeCount; i++) {
    86.             // 得到随机产生的验证码数字。
    87.             String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
    88.             // 用随机产生的颜色将验证码绘制到图像中。
    89.             red = random.nextInt(255);
    90.             green = random.nextInt(255);
    91.             blue = random.nextInt(255);
    92.             g.setColor(new Color(red, green, blue));
    93.             g.drawString(strRand, (i + 1) * x, codeY);
    94.             // 将产生的四个随机数组合在一起。
    95.             randomCode.append(strRand);
    96.         }
    97.         // 将四位数字的验证码保存到Session中。
    98.         code = randomCode.toString();
    99.     }
    100.     public void write(String path) throws IOException {
    101.         OutputStream sos = new FileOutputStream(path);
    102.         this.write(sos);
    103.     }
    104.     public void write(OutputStream sos) throws IOException {
    105.         ImageIO.write(buffImg, "png", sos);
    106.         sos.close();
    107.     }
    108.     public BufferedImage getBuffImg() {
    109.         return buffImg;
    110.     }
    111.     public String getCode() {
    112.         return code;
    113.     }
    114. }
    复制代码
  • 验证码生成 请求
    1. @Controller
    2. @RequestMapping("user")
    3. public class UserController {
    4.     /**
    5.      * 生成验证码
    6.      */
    7.                 @ResponseBody
    8.     @RequestMapping("verifyCode")
    9.     public Map<String, String> verifyCode(HttpServletRequest request) throws IOException {
    10.         Map<String,String> map = new HashMap<>();
    11.         // 1.使用工具类生成验证码
    12.         VerifyCode vc = new VerifyCode(120, 40, 4, 100);
    13.         String code = vc.getCode();
    14.         map.put("code", code);
    15.         // 2. 获取验证码的BufferedImage对象
    16.         BufferedImage captchaImage = vc.getBuffImg();
    17.         //4.将图片转为base64 [放入src,可以直接显示图片]
    18.         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    19.         ImageIO.write(captchaImage, "png", outputStream);
    20.         byte[] imageBytes = outputStream.toByteArray();
    21.         String image = "data:image/png;base64," + Base64Utils.encodeToString(imageBytes);
    22.         map.put("image", image);
    23.         return map;
    24.     }
    25. }
    复制代码
10.7 注册实现


  • 业务逻辑

  • Service
    1. @Service
    2. @Transactional
    3. public class UserServiceImpl implements UserService {
    4.     @Autowired
    5.     private UserDao userDao;
    6.     @Override
    7.     public void register(User user) {
    8.         User userDB = userDao.findByUserName(user.getUsername());
    9.         if (!ObjectUtils.isEmpty(userDB)) {
    10.             throw new RuntimeException("用户名已存在");
    11.         }
    12.         // 注册之前给密码进行加密
    13.         String passwordSecret = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
    14.         user.setPassword(passwordSecret);
    15.         userDao.save(user);
    16.     }
    17. }
    复制代码
  • mapper语句
    1. <select id="findByUserName" resultType="com.baizhi.entity.User">
    2.     select id,username,realname,password,gender from `user`
    3.     where username = #{username}
    4. </select>
    复制代码
  • api
    1. @Autowired
    2. private UserService userService;
    3. @RequestMapping("register")
    4. public String register(User user, String code, HttpSession session) {
    5.     log.debug("接受的验证码:{}", code);
    6.     log.debug("User:{}", user);
    7.     // 比较验证
    8.     try {
    9.         String sessionCode = session.getAttribute("code").toString();
    10.         if (!sessionCode.equalsIgnoreCase(code)) {
    11.             throw new RuntimeException("验证码输入错误!!!");
    12.         }
    13.         userService.register(user);
    14.     } catch (RuntimeException e) {
    15.         e.printStackTrace();
    16.         return "redirect:/register.jsp?msg=" + UriEncoder.encode(e.getMessage());
    17.     }
    18.     return "redirect:/login.jsp";
    19. }
    复制代码
10.8用户登录



  • login.jsp
    1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    2. <!DOCTYPE html>
    3. <html>
    4. <head>
    5.     <meta charset="UTF-8">
    6.     <title>Login Page</title>
    7.     <link rel="stylesheet" href="css/register.css">
    8. </head>
    9. <body>
    10. <h2>用户登录</h2>
    11. <h3 >${param.msg}</h3>
    12. <form action="${pageContext.request.contextPath}/employee/list" method="post">
    13.     <label for="username">用户名:</label><br>
    14.     <input type="text" id="username" name="username"><br>
    15.     <label for="password">密码:</label><br>
    16.     <input type="password" id="password" name="password"><br>
    17.     <input type="submit" value="登录">
    18.     <input type="button" onclick="window.location.href='register.jsp'"  value="注册">
    19. </form>
    20. </body>
    21. </html>
    复制代码
  • ServiceImpl
    1. @Override
    2. public User login(String username, String password) {
    3.     //1. 根据用户名查询数据库是否存在
    4.     User user = userDao.findByUserName(username);
    5.     //2.判断对象是否存在
    6.     if (ObjectUtils.isEmpty(user)) {
    7.         throw new RuntimeException("用户名输入错误!");
    8.     }
    9.     //3.判断密码正确性
    10.     String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
    11.     if (!user.getPassword().equals(digestPassword)) {
    12.         throw new RuntimeException("密码错误!");
    13.     }
    14.     return user;
    15. }
    复制代码
  • UserController
    1. @RequestMapping("login")
    2. public String login(String username, String password,HttpSession session) throws UnsupportedEncodingException {
    3.     log.debug("接受到的用户名:{},接收到的密码:{}", username, password);
    4.     try {
    5.         // 1.执行登录业务逻辑
    6.         User user = userService.login(username, password);
    7.         // 2.登录成功,保存用户信息
    8.         session.setAttribute("user", user);
    9.     } catch (Exception e) {
    10.         e.printStackTrace();
    11.         return "redirect:/login.jsp?msg=" + UriEncoder.encode(e.getMessage());
    12.     }
    13.     return "redirect:/emplist.jsp";
    14. }
    复制代码
10.9 员工列表展示


  • 在数据库查询所有员工信息
  • 在页面中进行展示


  • emplist.jsp
    1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    2. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    3. <%@ page language="java" contentType="text/html; charset=UTF-8"
    4.          pageEncoding="UTF-8" %>
    5. <!DOCTYPE html>
    6. <html>
    7. <head>
    8.     <title>用户列表</title>
    9.     <link rel="stylesheet" href="${pageContext.request.contextPath}/css/emplist.css">
    10. </head>
    11. <body>
    12.    
    13.         <h2>用户列表</h2>
    14.         <table>
    15.             <tr>
    16.                 <th>ID</th>
    17.                 <th>姓名</th>
    18.                 <th>性别</th>
    19.                 <th>薪水</th>
    20.                 <th>生日</th>
    21.                 <th>操作</th>
    22.             </tr>
    23.             <c:forEach var="employee" items="${requestScope.employees}">
    24.                 <tr>
    25.                     <td>${employee.id}</td>
    26.                     <td>${employee.name}</td>
    27.                     <td>${employee.gender?'男':'女'}</td>
    28.                     <td>${employee.salary}</td>
    29.                     <td><fmt:formatDate value="${employee.birthday}" pattern="yyyy-MM-dd"/></td>
    30.                      <td>
    31.                         <a target="_blank" href="https://www.cnblogs.com/javascript:;">删除</a>
    32.                         <a target="_blank" href="https://www.cnblogs.com/javascript:;">修改</a>
    33.                     </td>
    34.                 </tr>
    35.             </c:forEach>
    36.         </table>
    37.         <a target="_blank" href="https://www.cnblogs.com/javascript:;">添加员工信息</a>
    38.    
    39. </body>
    40. </html>
    复制代码
  • emplist.css
    1. body {
    2.     font-family: Arial, sans-serif;
    3.     margin: 0;
    4.     padding: 0;
    5. }
    6. #container {
    7.     max-width: 800px;
    8.     margin: 0 auto;
    9.     padding: 20px;
    10. }
    11. h2 {
    12.     text-align: center;
    13. }
    14. table {
    15.     width: 100%;
    16.     border-collapse: collapse;
    17.     margin-bottom: 20px;
    18. }
    19. th, td {
    20.     padding: 10px;
    21.     text-align: left;
    22.     border: 1px solid #ccc;
    23. }
    24. thead {
    25.     background-color: #f2f2f2;
    26. }
    27. div > button {
    28.     margin: 5px;
    29.     padding: 5px 10px;
    30.     border: none;
    31.     background-color: #007bff;
    32.     color: #fff;
    33.     cursor: pointer;
    34. }
    35. div > button:hover {
    36.     background-color: #0056b3;
    37. }
    38. select, button {
    39.     padding: 5px;
    40. }
    41. div > span {
    42.     margin: 0 10px;
    43.     font-weight: bold;
    44. }
    45. label {
    46.     font-weight: bold;
    47. }
    复制代码
  • Service
    1. @Service
    2. @Transactional
    3. public class EmployeeServiceImpl implements EmployeeService {
    4.     private final EmployeeDao employeeDao;
    5.     @Autowired
    6.     public EmployeeServiceImpl(EmployeeDao employeeDao) {
    7.         this.employeeDao = employeeDao;
    8.     }
    9.     @Override
    10.     public List<Employee> list() {
    11.         return employeeDao.list();
    12.     }
    13. }
    复制代码
  • EmployeeController
    1. @Controller
    2. @RequestMapping("employee")
    3. public class EmployeeController {
    4.     private EmployeeService employeeService;
    5.     @Autowired
    6.     public EmployeeController(EmployeeService employeeService) {
    7.         this.employeeService = employeeService;
    8.     }
    9.     /**
    10.      * 员工列表
    11.      *
    12.      * @return
    13.      */
    14.     @RequestMapping("list")
    15.     public String listEmployee(HttpServletRequest request, Model model) {
    16.         //1. 获取员工列表
    17.         List<Employee> employees = employeeService.list();
    18. //        request.setAttribute("employees", employees);
    19.         model.addAttribute("employees", employees);
    20.         return "emplist";
    21.     }
    22. }
    复制代码
10.10 添加员工信息


  • 在EmplyeeController开发一个添加方法
  • 接收员工信息
  • 将员工信息保存到数据库
  • 跳转到员工列表展示数据


  • addEmp.jsp
    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2.          pageEncoding="UTF-8" %>
    3. <!DOCTYPE html>
    4. <html>
    5. <head>
    6.     <title>添加员工</title>
    7.     <link rel="stylesheet" href="css/addEmp.css">
    8. </head>
    9. <body>
    10.     <h2>添加员工</h2>
    11.    
    12.         <form action="${pageContext.request.contextPath}/employee/add" method="post">
    13.             <table>
    14.                 <tr>
    15.                     <td>姓名:</td>
    16.                     <td><input type="text" id="name" name="name"></td>
    17.                 </tr>
    18.                 <tr>
    19.                     <td>薪水:</td>
    20.                     <td><input type="text" id="salary" name="salary"></td>
    21.                 </tr>
    22.                 <tr>
    23.                     <td>生日:</td>
    24.                     <td><input type="text" id="birthday" name="birthday"></td>
    25.                 </tr>
    26.                 <tr>
    27.                     <td>性别:</td>
    28.                     <td>
    29.                         <select name="gender" >
    30.                             <option value="1">男</option>
    31.                             <option value="0">女</option>
    32.                         </select>
    33.                     </td>
    34.                 </tr>
    35.                 <tr>
    36.                     <td colspan="2"><input type="submit" value="添加"></td>
    37.                 </tr>
    38.             </table>
    39.         </form>
    40.    
    41. </body>
    42. </html>
    复制代码
  • addEmp.css
    1. body {
    2.     font-family: Arial, sans-serif;
    3.     margin: 0;
    4.     padding: 0;
    5. }
    6. #container {
    7.     max-width: 800px;
    8.     margin: 0 auto;
    9.     padding: 20px;
    10. }
    11. h2 {
    12.     text-align: center;
    13. }
    14. table {
    15.     width: 100%;
    16.     border-collapse: collapse;
    17.     margin-bottom: 20px;
    18.     color: #212529;
    19. }
    20. td, th {
    21.     vertical-align: top;
    22.     padding: 10px;
    23.     text-align: left;
    24.     border: 1px solid #ccc;
    25. }
    26. input[type="text"], input[type="date"], select {
    27.     width: 60%;
    28.     padding: .375rem .75rem;
    29.     border: 1px solid #ced4da;
    30.     border-radius: .25rem;
    31. }
    32. input[type="submit"] {
    33.     color: #fff;
    34.     background-color: #007bff;
    35.     border-color: #007bff;
    36.     padding: .375rem .75rem;
    37.     border-radius: .25rem;
    38. }
    复制代码
  • EmployeeDaomapper.xml
    1. <insert id="add" parameterType="Employee" useGeneratedKeys="true" keyProperty="id">
    2.     INSERT INTO `ems`.`employee`(`id`, `name`, `birthday`, `salary`, `gender`) VALUES (#{id},#{name},#{birthday},#{salary},#{gender});
    3. </insert>
    复制代码
  • EmployeeServiceImpl
    1. public void addEmployee(Employee employee) {
    2.     employeeDao.add(employee);
    3. }
    复制代码
  • Controller
    1. @RequestMapping("add")
    2. public String addEmployee(Employee employee) {
    3.     log.debug("员工信息:{}", employee);
    4.     //1. 保存员工信息
    5.     employeeService.addEmployee(employee);
    6.     return "redirect:/employee/list";
    7. }
    复制代码
10.11 更新员工信息


  • 显示员工信息

    • 根据id查询员工信息
    • 将对象放进作用域
    • 跳转到更新页面

  • UpdateEmp.jsp
    1. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    2. <%@ page language="java" contentType="text/html; charset=UTF-8"
    3.          pageEncoding="UTF-8" %>
    4. <!DOCTYPE html>
    5. <html>
    6. <head>
    7.     <title>修改员工信息</title>
    8.     <link rel="stylesheet" href="${pageContext.request.contextPath}/css/updateEmp.css">
    9. </head>
    10. <body>
    11.    
    12.         <h2>修改员工信息</h2>
    13.         <form action="${pageContext.request.contextPath}/employee/update" method="post">
    14.             <input type="text" id="id" name="id" value="${employee.id}" >
    15.             <label for="name">姓名:</label><br>
    16.             <input type="text" id="name" name="name" value="${employee.name}"><br>
    17.             <label for="gender">性别:</label><br>
    18.             <select id="gender" name="gender">
    19.                 <option value="1" ${employee.gender?'selected':''}>男</option>
    20.                 <option value="0" ${!employee.gender?'selected':''}>女</option>
    21.             </select><br>
    22.             <label for="salary">薪水:</label><br>
    23.             <input type="text" id="salary" name="salary" value="${employee.salary}"><br>
    24.             <label for="birthday">生日:</label><br>
    25.             <input type="text" id="birthday" name="birthday" value="<fmt:formatDate value='${employee.birthday}' pattern='yyyy/MM/dd'/>"/><br>
    26.             <input type="submit" value="提交">
    27.         </form>
    28.    
    29. </body>
    30. </html>
    复制代码
  • UpdateEmp.css
    1. body {
    2.     font-family: Arial, sans-serif;
    3. }
    4. #container {
    5.     width: 300px;
    6.     margin: 0 auto;
    7.     padding: 20px;
    8.     border: 1px solid #ccc;
    9.     border-radius: 5px;
    10.     background-color: #f8f8f8;
    11. }
    12. h2 {
    13.     text-align: center;
    14.     color: #333;
    15. }
    16. label {
    17.     font-weight: bold;
    18.     color: #555;
    19. }
    20. input[type="text"], input[type="date"],select {
    21.     width: 70%;
    22.     padding: 10px;
    23.     margin: 5px 0 15px;
    24.     border: 1px solid #ccc;
    25.     border-radius: 3px;
    26. }
    27. input[type="submit"] {
    28.     width: 100%;
    29.     padding: 10px;
    30.     color: white;
    31.     background-color: #007BFF;
    32.     border: none;
    33.     border-radius: 3px;
    34.     cursor: pointer;
    35. }
    36. input[type="submit"]:hover {
    37.     background-color: #0056b3;
    38. }
    复制代码
  • Controller
    1. @RequestMapping("detail")
    2. public String detailEmployee(Integer id, Model model) {
    3.     log.debug("接收的id:{}",id);
    4.     Employee employee = employeeService.idByEmployee(id);
    5.     model.addAttribute("employee", employee);
    6.     return "updateEmp";
    7. }
    复制代码
  • 更改员工信息

    • 获取更新后的员工信息
    • 更新数据库

  • Controller
    1. @RequestMapping("update")
    2. public String updateEmployee(Employee employee) {
    3.     log.debug("修改的员工信息:{}", employee);
    4.     employeeService.updateEmployee(employee);
    5.     return "redirect:/employee/list";
    6. }
    复制代码
10.12 删除员工


  • 传递id给后端进行数据库删除
  • 返回employee/list重新查数据库刷新


  • emplist.jsp
    1. <a target="_blank" href="https://www.cnblogs.com/javascript:;" onclick="deleteEmployee()">删除</a>
    复制代码
  • Controller
    1. @RequestMapping("delete")
    2. public String deleteEmployee(Integer id) {
    3.     log.debug("接收的id:{}", id);
    4.     employeeService.deleteEmployee(id);
    5.     return "redirect:/employee/list";
    6. }
    复制代码
  • mapper
    1. <delete id="deleteEmployee">
    2.     delete from `employee`where id =#{id}
    3. </delete>
    复制代码

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

笑看天下无敌手

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表