0


手把手带你搭建SpringBoot员工管理系统(呕心肝下65k字保姆级教学附源码,建议收藏!!)

img

个人主页:BoBooY的CSDN博客_Java领域博主

1.前言:在上一期中手把手带大家搭建了模拟数据库的SpringBoot员工管理系统(无数据库),相信大家已经对整体项目已经有了大体的的了解,这一期我来带大家一步一步的搭建 带有Druid数据源并整合了MySQL数据库的完整基础版员工管理系统。
2.读前须知:本期项目着重讲解如何将项目整合数据库,但搭建项目的每一步的代码和步骤也都一一罗列了出来供未阅读过上一期内容的小伙伴们参考,建议小伙伴们先阅读 上一期内容(可以着重看修改前端静态资源的内容,因为本期不再过多阐述),文章基本将所有项目的代码都贴了出来,如果有需要源码打包的小伙伴,文末可以自取。搭建项目过程中遇到的各种常见问题汇总在下方链接中,遇到问题时可以参考。
3.上期内容:无数据库版本员工管理系统搭建链接(重要,建议参考阅读!!)https://blog.csdn.net/qq_58233406/article/details/126837617
4.项目搭建问题汇总(重要)https://blog.csdn.net/qq_58233406/article/details/126914605

文章目录

员工管理系统

1、初始化项目

1.1、新建项目

在这里插入图片描述

1.2、导入静态资源

静态资源链接:https://blog.csdn.net/qq_58233406/article/details/126838809

在这里插入图片描述

1.3、修改数据库版本

springboot2.6.11默认的mysql版本为8.0.30,本人mysql用的版本是5.7

<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version><scope>runtime</scope></dependency>

1.4、初始化首页

  • 编写MVC扩展配置,设置首页
packagecom.bobooy.ems.config;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.ViewControllerRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;/**
 * @author BoBooY
 * @date 2022/9/18 21:30
 */@ConfigurationpublicclassMyMvcConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddViewControllers(ViewControllerRegistry registry){
        registry.addViewController("/").setViewName("index");
         registry.addViewController("/main.html").setViewName("dashboard");//点击首页发送 /main.html请求}}

1.5、国际化

  • 设置项目编码为UTF-8
  • 编写国际化配置文件
  • 编写配置- login.properties : 默认login.btn=请登录login.username=用户名login.password=密码login.remember=记住我login.tip=请登录- login_en_US.properties:英语login.btn=sign inlogin.username=usernamelogin.password=passwordlogin.remember=remember melogin.tip=Please sign in- login_zh_CH.propertieslogin.btn=请登录login.username=用户名login.password=密码login.remember=记住我login.tip=请登录
  • 配置messages路径(注意空格,笔记代码只记录部分关键代码)#国际化配置messages:basename: i18n.login
  • 配置国际化- 修改前端页面中英文的请求<!-- Thymeleaf传参不用 ? 而是使用 (key=value) --><aclass="btn btn-sm"th:href="@{/index.html(lang='zh_CH')}">中文</a><aclass="btn btn-sm"th:href="@{/index.html(lang='en_US')}">English</a>- 编写处理国际化的配置类packagecom.springboot05ems.config;importorg.springframework.web.servlet.LocaleResolver;importorg.thymeleaf.util.StringUtils;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.util.Locale;/** * @author BoBooY * @date 2022/9/5 21:06 */publicclassMyLocaleResolverimplementsLocaleResolver{@OverridepublicLocaleresolveLocale(HttpServletRequest request){String lang = request.getParameter("lang");Locale locale =Locale.getDefault();//如果请求不为空if(!StringUtils.isEmpty(lang)){//分割请求参数String[] s = lang.split("_");//国家,地区 locale =newLocale(s[0],s[1]);}return locale;}@OverridepublicvoidsetLocale(HttpServletRequest request,HttpServletResponse response,Locale locale){}}- 在个人的配置类(MyMvcConfig)中注册bean@BeanpublicLocaleResolverlocaleResolver(){returnnewMyLocaleResolver();}- 修改MyMvcConfigregistry.addViewController("/index.html").setViewName("index");

在这里插入图片描述

2、登录功能实现

3.1、设计数据库表

CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot` /*!40100 DEFAULT
CHARACTER SET utf8 */;

USE `springboot`;

/*Table structure for table `department` */
DROP TABLE IF EXISTS `department`;

CREATE TABLE `department` (
`id` int(3) NOT NULL AUTO_INCREMENT COMMENT '部门id',
`department_name` varchar(20) NOT NULL COMMENT '部门名字',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=106 DEFAULT CHARSET=utf8;
/*Data for the table `department` */

insert into `department`(`id`,`department_name`) values (101,'技术部'),
(102,'销售部'),(103,'售后部'),(104,'后勤部'),(105,'运营部');

/*Table structure for table `employee` */
DROP TABLE IF EXISTS `employee`;

CREATE TABLE `employee` (
`id` int(5) NOT NULL AUTO_INCREMENT COMMENT '雇员id',
`last_name` varchar(100) NOT NULL COMMENT '名字',
`email` varchar(100) NOT NULL COMMENT '邮箱',
`gender` int(2) NOT NULL COMMENT '性别1 男, 0 女',
`department` int(3) NOT NULL COMMENT '部门id',
`birth` datetime NOT NULL COMMENT '生日',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8;
/*Data for the table `employee` */

insert into
`employee`(`id`,`last_name`,`email`,`gender`,`department`,`birth`) values
(1001,'张三','[email protected]',1,101,'2021-03-06 15:04:33'),(1002,'李
四','[email protected]',1,102,'2021-03-06 15:04:36'),(1003,'王
五','[email protected]',0,103,'2021-03-06 15:04:37'),(1004,'赵
六','[email protected]',1,104,'2021-03-06 15:04:39'),(1005,'孙
七','[email protected]',0,105,'2021-03-06 15:04:45');

CREATE TABLE `user` (
`id` int(3) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`userName` varchar(20) NOT NULL COMMENT '用户名字',
`pwd` varchar(20) NOT NULL COMMENT '用户密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*Data for the table `user` */

insert into
`user`(`id`,`userName`,`pwd`) values
(1,'admin','123');

3.2、IDEA连接数据库

在这里插入图片描述

3.3、编写实体类

  • User 类
packagecom.bobooy.ems.pojo;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;/**
 * @author BoBooY
 * @date 2022/9/18 22:17
 */@Data@NoArgsConstructor@AllArgsConstructorpublicclassUser{privateint id;privateString userName;privateString pwd;}
  • Department 类
packagecom.bobooy.ems.pojo;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;//部门类@Data@NoArgsConstructor@AllArgsConstructorpublicclassDepartment{privateInteger id;privateString departmentName;}
  • Employee 类
packagecom.bobooy.ems.pojo;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;importjava.util.Date;//员工类@Data@AllArgsConstructor@NoArgsConstructorpublicclassEmployee{privateInteger id;privateString lastName;privateString email;privateInteger gender;privateDepartment department;//这里重点注意类型为 Department// @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")privateDate birth;}

3.4、导入 druid 数据源的依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.6</version></dependency>

3.5、导入log4j 日志依赖

<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency>

3.6、配置Druid数据源

  • application.yaml
spring:datasource:username: root
    password:1234url: jdbc:mysql://localhost:3306/springboot?useSSL=true&useUnicode=true&characterEncoding=utf8driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource # 自定义数据源#数据源#Spring Boot 默认是不注入这些属性值的,需要自己绑定#druid 数据源专有配置initialSize:5minIdle:5maxActive:20maxWait:60000timeBetweenEvictionRunsMillis:60000minEvictableIdleTimeMillis:300000validationQuery: SELECT 1 FROM DUAL
    testWhileIdle:truetestOnBorrow:falsetestOnReturn:falsepoolPreparedStatements:true#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4jfilters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize:20useGlobalDataSourceStat:trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  • 编写配置类 Druid.config
packagecom.bobooy.ems.config;importcom.alibaba.druid.pool.DruidDataSource;importcom.alibaba.druid.support.http.StatViewServlet;importcom.alibaba.druid.support.http.WebStatFilter;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.boot.web.servlet.FilterRegistrationBean;importorg.springframework.boot.web.servlet.ServletRegistrationBean;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importjavax.sql.DataSource;importjava.util.Arrays;importjava.util.HashMap;importjava.util.Map;/**
 * @author BoBooY
 * @date 2022/9/17 17:19
 */@ConfigurationpublicclassDruidConfig{/**
     * 将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
     * 绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
     *
     * @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
     * 前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
     */@ConfigurationProperties(prefix ="spring.datasource")@BeanpublicDataSourcedruidDataSource(){returnnewDruidDataSource();}// 配置 Druid 监控管理后台的Servlet;// 内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式@BeanpublicServletRegistrationBeanstatViewServlet(){ServletRegistrationBean bean =newServletRegistrationBean(newStatViewServlet(),"/druid/*");// 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet的父类 com.alibaba.druid.support.http.ResourceServlet 中找到Map<String,String> initParams =newHashMap<>();
        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");// deny:Druid 后台拒绝谁访问// initParams.put("deny", "192.168.1.20");表示禁止此ip访问

        bean.setInitParameters(initParams);return bean;}// 配置 Druid 监控 之  web 监控的 filter// WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计@BeanpublicFilterRegistrationBeanwebStatFilter(){FilterRegistrationBean bean =newFilterRegistrationBean();
        bean.setFilter(newWebStatFilter());// exclusions:设置哪些请求进行过滤排除掉,从而不进行统计HashMap<String,String> initParams =newHashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*,/jdbc/*");
        bean.setInitParameters(initParams);// "/*" 表示过滤所有请求
        bean.setUrlPatterns(Arrays.asList("/*"));return bean;}}
  • 测试

在这里插入图片描述

在这里插入图片描述

3.7、编写 DAO层

  • UserMapper
packagecom.bobooy.ems.mapper;importcom.bobooy.ems.pojo.User;importorg.apache.ibatis.annotations.Mapper;importorg.springframework.stereotype.Repository;/**
 * @author BoBooY
 * @date 2022/9/18 22:26
 */@Mapper@RepositorypublicinterfaceUserMapper{UsergetUser(String userName);}
  • 在 resources目录下新建mybatis / mapper目录下新建UserMapper.xml文件
<?xml version="1.0" encoding="UTF8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.bobooy.ems.mapper.UserMapper"><selectid="getUserById"resultType="User"parameterType="">
        select * from user where `userName`=#{userName}
    </select></mapper>

3.8、配置 Mybatis

  • application.yaml
#配置MybatisMybatis:mapper-locations: classpath:mybatis/mapper/*.xmltype-aliases-package: com.bobooy.ems.pojo

3.9、编写Service层

  • UserService
publicinterfaceUserService{UsergetUser(String userName);}
  • UserServiceImpl
packagecom.bobooy.ems.service;importcom.bobooy.ems.mapper.UserMapper;importcom.bobooy.ems.pojo.User;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;/**
 * @author BoBooY
 * @date 2022/9/19 19:39
 */@ServicepublicclassUserServiceImplimplementsUserService{@AutowiredprivateUserMapper userMapper;@OverridepublicUsergetUser(String userName){return userMapper.getUser(userName);}}

3.10、编写Controller层

  • UserController
packagecom.bobooy.ems.controller;importcom.bobooy.ems.mapper.UserMapper;importcom.bobooy.ems.pojo.User;importcom.bobooy.ems.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.*;importjavax.servlet.http.HttpSession;/**
 * @author BoBooY
 * @date 2022/9/19 17:05
 */@ControllerpublicclassUserController{@AutowiredUserService userService;@PostMapping("/user/login")publicStringlogin(@RequestParam("username")String userName,@RequestParam("password")String pwd,Model model,HttpSession session){User user = userService.getUser(userName);if(user.getUserName().equals(userName)&& user.getPwd().equals(pwd)){
            session.setAttribute("loginUser",user);return"redirect:/main.html";}else{
            model.addAttribute("msg","用户名或密码错误!");return"index";}}}
  • 编写MVC扩展
registry.addViewController("/main.html").setViewName("dashboard");

3.11、修改前端 顶部栏获取Session

<aclass="navbar-brand col-sm-3 col-md-2 mr-0"th:href="@{http://getbootstrap.com/docs/4.0/examples/dashboard/#}"th:text="${session.loginUser.getUserName()}"></a>

在这里插入图片描述

3.12、测试

  • 登录页面

在这里插入图片描述

  • 主页面

在这里插入图片描述

3、登录拦截

  • 编写拦截器LoginHandlerInterceptor
packagecom.bobooy.ems.config;importorg.springframework.web.servlet.HandlerInterceptor;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;/**
 * @author BoBooY
 * @date 2022/9/30 19:50
 */publicclassLoginHandlerInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequest request,HttpServletResponse response,Object handler)throwsException{HttpSession session = request.getSession();if(session.getAttribute("loginUser")==null){
            request.setAttribute("msg","您没有权限,请先登录");
            request.getRequestDispatcher("/index.html").forward(request,response);returnfalse;}else{returntrue;}}}
  • 在配置类中注册拦截器MyMvcConfig
//配置拦截器@OverridepublicvoidaddInterceptors(InterceptorRegistry registry){
    registry.addInterceptor(newLoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/index.html","/user/login","/css/**","/img/**","/js/**");}
  • 测试

在这里插入图片描述

4、员工管理页面

4.1、查询全部员工

DAO层

  • 编写EmployeeMapper
packagecom.bobooy.ems.mapper;importcom.bobooy.ems.pojo.Employee;importorg.apache.ibatis.annotations.Mapper;importorg.springframework.stereotype.Repository;importjava.util.Collection;/**
 * @author BoBooY
 * @date 2022/9/26 23:23
 */@Mapper@RepositorypublicinterfaceEmployeeMapper{//查询全体员工信息publicCollection<Employee>getAll();}
  • 编写EmployeeMapper.xml
<?xml version="1.0" encoding="UTF8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.bobooy.ems.mapper.EmployeeMapper"><selectid="getAll"resultMap="EmployeeDepartment">
        select e.id eid, e.last_Name eName, e.email email, e.gender gender,d.id did,e.birth birth, d.department_name dName
        from employee e
        join department d
        on e.department = d.id
    </select><resultMapid="EmployeeDepartment"type="Employee"><resultproperty="id"column="eid"/><resultproperty="lastName"column="eName"/><resultproperty="email"column="email"/><resultproperty="gender"column="gender"/><resultproperty="birth"column="birth"/><associationproperty="department"javaType="Department"><resultproperty="id"column="did"/><resultproperty="departmentName"column="dName"/></association></resultMap></mapper>

service层

  • 编写EmployeeServicepackagecom.bobooy.ems.service;importcom.bobooy.ems.mapper.EmployeeMapper;importcom.bobooy.ems.pojo.Employee;importorg.springframework.stereotype.Service;importjava.util.Collection;/** * @author BoBooY * @date 2022/9/26 23:44 */publicinterfaceEmployeeService{//查询全体员工信息publicCollection<Employee>getAll();}- EmployeeServiceImplpackagecom.bobooy.ems.service;importcom.bobooy.ems.mapper.EmployeeMapper;importcom.bobooy.ems.pojo.Employee;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importjava.util.Collection;/** * @author BoBooY * @date 2022/9/26 23:45 */@ServicepublicclassEmployeeServiceImplimplementsEmployeeService{@OverridepublicCollection<Employee>getAll(){return employeeMapper.getAll();}}> controller层- 编写EmployeeContollerpackagecom.bobooy.ems.controller;importcom.bobooy.ems.mapper.EmployeeMapper;importcom.bobooy.ems.pojo.Employee;importcom.bobooy.ems.service.EmployeeService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importjava.util.Collection;/** * @author BoBooY * @date 2022/9/26 23:20 */@ControllerpublicclassEmployeeController{@AutowiredprivateEmployeeService employeeService;@RequestMapping("/emps")publicStringlist(Model model){Collection<Employee> employees = employeeService.getAll(); model.addAttribute("emps",employees);return"emp/list";}}> 测试

在这里插入图片描述

4.2、添加员工

4.2.1、跳转添加页面

DAO层

  • 编写 DepartmentMapper
packagecom.bobooy.ems.mapper;importcom.bobooy.ems.pojo.Department;importorg.apache.ibatis.annotations.Mapper;importorg.springframework.stereotype.Repository;importjava.util.Collection;/**
 * @author BoBooY
 * @date 2022/9/27 0:01
 */@Mapper@RepositorypublicinterfaceDepartmentMapper{//获取所有部门的信息Collection<Department>getDepartments();// 通过ID查询部门DepartmentgetDepartmentById(Integer id);}
  • DepartmentMapper.xml
<?xml version="1.0" encoding="UTF8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.bobooy.ems.mapper.DepartmentMapper"><selectid="getDepartments"resultType="Department">
        select * from department
    </select><selectid="getDepartmentById"resultType="Department"parameterType="Integer">
        select * from department where id = #{id}
    </select></mapper>
  • 在 application.yaml中开启 Myabtis 驼峰命名映射 注意空格
configuration:map-underscore-to-camel-case:true#开启驼峰命名

Service层

  • DepartmentService
packagecom.bobooy.ems.service;importcom.bobooy.ems.pojo.Department;importjava.util.Collection;/**
 * @author BoBooY
 * @date 2022/10/2 10:31
 */publicinterfaceDepartmentService{//获取所有部门的信息Collection<Department>getDepartments();// 通过ID查询部门DepartmentgetDepartmentById(Integer id);}
  • DepartmentServiceImpl
packagecom.bobooy.ems.service;importcom.bobooy.ems.mapper.DepartmentMapper;importcom.bobooy.ems.pojo.Department;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importjava.util.Collection;/**
 * @author BoBooY
 * @date 2022/10/2 10:32
 */@ServicepublicclassDepartmentServiceImplimplementsDepartmentService{@AutowiredprivateDepartmentMapper departmentMapper;@OverridepublicCollection<Department>getDepartments(){return departmentMapper.getDepartments();}@OverridepublicDepartmentgetDepartmentById(Integer id){return departmentMapper.getDepartmentById(id);}}

Controller层

  • 在EmployeeController中处理 ”/add“请求
@AutowiredprivateDepartmentService departmentService;@GetMapping("/add")publicStringadd(Model model){Collection<Department> departments = departmentService.getDepartments();
    model.addAttribute("depts",departments);System.out.println(departments);return"emp/add";}

测试

在这里插入图片描述

4.2.2、处理添加员工请求

DAO层

  • 编写EmployeeMapper
//添加员工publicintsave(Employee employee);
  • EmployeeMapper.xml
<insertid="save"parameterType="Employee">
    insert into employee(`last_name`, `email`, `gender`, `department`, `birth`)
    values (#{lastName}, #{email}, #{gender}, #{department.id}, #{birth})
</insert>

service层

  • EmployeeService
//添加员工publicintsave(Employee employee);
  • EmployeeServiceImpl
@Overridepublicintsave(Employee employee){return employeeMapper.save(employee);}

controller层

  • EmployeeController
//添加员工@RequestMapping("/addEmp")publicStringaddEmp(Employee employee){int save = employeeService.save(employee);if(save >0){System.out.println("添加成功!");}else{System.out.println("添加失败!");}return"redirect:/emps";}

设置日期格式

  • application.yaml(注意空格)
#日期格式配置mvc:format:date: yyyy-MM-dd HH:mm

测试:添加员工

在这里插入图片描述

在这里插入图片描述

成功!

4.3、修改员工

Dao层

  • 编写 EmployeeMapper
//修改员工publicintupdateEmployee(Employee employee);// 通过ID查询员工publicEmployeegetEmployee(Integer id);
  • EmployeeMapper.xml
<selectid="getEmployee"parameterType="int"resultMap="EmployeeDepartment">
    select e.id eid, e.last_Name eName, e.email email, e.gender gender,d.id did,e.birth birth, d.department_name dName
    from employee e
    join department d
    on e.department = d.id
    where e.id = #{id}
</select><updateid="updateEmployee"parameterType="Employee">
    update employee set `last_name`=#{lastName},`email`=#{email},`gender`=#{gender},`department`=#{department.id},`birth`=#{birth} where `id` = #{id}
</update>

service层

  • EmployeeService
// 通过ID查询员工publicEmployeegetEmployee(Integer id);//修改员工publicintupdateEmployee(Employee employee);
  • EmployeeServiceImpl
@OverridepublicEmployeegetEmployee(Integer id){return employeeMapper.getEmployee(id);}@OverridepublicintupdateEmployee(Employee employee){return employeeMapper.updateEmployee(employee);}

Controller层

  • EmployeeController
//跳转修改页面@GetMapping("/update/{id}")publicStringupdate(@PathVariable("id")int id,Model model){Employee employee = employeeService.getEmployee(id);
    model.addAttribute("emp",employee);Collection<Department> departments = departmentService.getDepartments();
    model.addAttribute("departments",departments);return"emp/update";}//修改员工信息@PostMapping("/updateEmp")publicStringupdate(Employee employee){int update = employeeService.updateEmployee(employee);if(update >0){System.out.println("修改成功");}else{System.out.println("修改失败");}return"redirect:/emps";}

测试:修改id为 1012 的员工部门为 后勤部 性别为男

  • 修改前:

在这里插入图片描述

  • 修改页面:

在这里插入图片描述

  • 修改后:

在这里插入图片描述

成功!

4.4、删除员工

Dao层

  • EmployeeMapper
// 删除员工publicintdelete(Integer id);
  • EmployeeMapper.xml
<deleteid="delete"parameterType="int">
    delete from employee where `id` = #{id}
</delete>

service层

  • EmployeeService
// 删除员工publicintdelete(Integer id);
  • EmployeeServiceImpl
@Overridepublicintdelete(Integer id){return employeeMapper.delete(id);}

controller层

  • EmployeeController
//删除员工@RequestMapping("/delete/{id}")publicStringdelete(@PathVariable("id")int id){int delete = employeeService.delete(id);if(delete >0)System.out.println("删除成功!");else{System.out.println("删除失败!");}return"redirect:/emps";}

测试:删除id为1011的员工

  • 删除前

在这里插入图片描述

  • 删除后

在这里插入图片描述

5、退出登录

  • UserController
//退出登录@RequestMapping("/logout")publicStringlogout(HttpSession session){
    session.invalidate();//使当前session失效return"redirect:/index.html";}
  • 测试:退出后 直接访问登录页面

在这里插入图片描述

项目成功搭建完成!

6、源码链接

GitHub地址:https://github.com/BoBooY-GitHub/EMS
百度网盘地址:https://pan.baidu.com/s/1kNjoxhtyrlBd1ww0RG1jrQ 验证码:g1ex

尾言:到这里本期内容也接近尾声啦,小伙伴们看到这里是不是感觉很简单呢,恭喜你完成了一个SpringBoot基础项目的搭建,后续可以继续往这个项目中添加你想要的功能,也可以当做一个模板来使用,对于初学者来说可以把这个项目当做一个参考,便于以后开发SpringBoot的项目。

最后,创作不易,如果本文的内容对您有帮助,还望客官可以三连支持一下博主,👍(点赞)+✏️(评论)+⭐️(收藏)是我创作的巨大动力!如果有本项目或者Java相关的问题,可以关注私信一下博主,随时为您解答!再次感谢小伙伴们的支持,我们下期再见!

相关教程:
SpringBoot 快速入门https://blog.csdn.net/qq_58233406/article/details/126689564
SpringBoot Web开发https://blog.csdn.net/qq_58233406/article/details/126719171
SpringBoot 整合数据库https://blog.csdn.net/qq_58233406/article/details/126914820

img


本文转载自: https://blog.csdn.net/qq_58233406/article/details/127174418
版权归原作者 -BoBooY- 所有, 如有侵权,请联系我们删除。

“手把手带你搭建SpringBoot员工管理系统(呕心肝下65k字保姆级教学附源码,建议收藏!!)”的评论:

还没有评论