员工管理系统
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扩展配置,设置首页
package com.bobooy.ems.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author BoBooY
* @date 2022/9/18 21:30
*/
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(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 in login.username=username login.password=password login.remember=remember me login.tip=Please sign in
- login_zh_CH.properties
login.btn=请登录 login.username=用户名 login.password=密码 login.remember=记住我 login.tip=请登录
配置messages路径(注意空格,笔记代码只记录部分关键代码)
#国际化配置 messages: basename: i18n.login
配置国际化
- 修改前端页面中英文的请求
<!-- Thymeleaf传参不用 ? 而是使用 (key=value) --> <a class="btn btn-sm" th:href="@{/index.html(lang='zh_CH')}">中文</a> <a class="btn btn-sm" th:href="@{/index.html(lang='en_US')}">English</a>
- 编写处理国际化的配置类
package com.springboot05ems.config; import org.springframework.web.servlet.LocaleResolver; import org.thymeleaf.util.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; /** * @author BoBooY * @date 2022/9/5 21:06 */ public class MyLocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { String lang = request.getParameter("lang"); Locale locale = Locale.getDefault(); //如果请求不为空 if(!StringUtils.isEmpty(lang)) { //分割请求参数 String[] s = lang.split("_"); //国家,地区 locale = new Locale(s[0],s[1]); } return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { } }
- 在个人的配置类(MyMvcConfig)中注册bean
@Bean public LocaleResolver localeResolver() { return new MyLocaleResolver(); }
- 修改MyMvcConfig
registry.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,'张三','243357594@qq.com',1,101,'2021-03-06 15:04:33'),(1002,'李
四','243357594@qq.com',1,102,'2021-03-06 15:04:36'),(1003,'王
五','243357594@qq.com',0,103,'2021-03-06 15:04:37'),(1004,'赵
六','243357594@qq.com',1,104,'2021-03-06 15:04:39'),(1005,'孙
七','243357594@qq.com',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 类
package com.bobooy.ems.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author BoBooY
* @date 2022/9/18 22:17
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String userName;
private String pwd;
}
- Department 类
package com.bobooy.ems.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//部门类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
- Employee 类
package com.bobooy.ems.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
//员工类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender;
private Department department; //这里重点注意类型为 Department
// @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
private Date 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: 1234
url: jdbc:mysql://localhost:3306/springboot?useSSL=true&useUnicode=true&characterEncoding=utf8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource # 自定义数据源
#数据源
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- 编写配置类 Druid.config
package com.bobooy.ems.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author BoBooY
* @date 2022/9/17 17:19
*/
@Configuration
public class DruidConfig {
/**
* 将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
* 绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
*
* @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
* 前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
// 配置 Druid 监控管理后台的Servlet;
// 内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
Map<String, String> initParams = new HashMap<>();
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数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
// exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
HashMap<String, String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*,/jdbc/*");
bean.setInitParameters(initParams);
// "/*" 表示过滤所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
- 测试
3.7、编写 DAO层
- UserMapper
package com.bobooy.ems.mapper;
import com.bobooy.ems.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
/**
* @author BoBooY
* @date 2022/9/18 22:26
*/
@Mapper
@Repository
public interface UserMapper {
User getUser(String userName);
}
- 在 resources目录下新建mybatis / mapper目录下新建UserMapper.xml文件
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bobooy.ems.mapper.UserMapper">
<select id="getUserById" resultType="User" parameterType="">
select * from user where `userName`=#{userName}
</select>
</mapper>
3.8、配置 Mybatis
- application.yaml
#配置Mybatis
Mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.bobooy.ems.pojo
3.9、编写Service层
- UserService
public interface UserService {
User getUser(String userName);
}
- UserServiceImpl
package com.bobooy.ems.service;
import com.bobooy.ems.mapper.UserMapper;
import com.bobooy.ems.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author BoBooY
* @date 2022/9/19 19:39
*/
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public User getUser(String userName) {
return userMapper.getUser(userName);
}
}
3.10、编写Controller层
- UserController
package com.bobooy.ems.controller;
import com.bobooy.ems.mapper.UserMapper;
import com.bobooy.ems.pojo.User;
import com.bobooy.ems.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
/**
* @author BoBooY
* @date 2022/9/19 17:05
*/
@Controller
public class UserController {
@Autowired
UserService userService;
@PostMapping("/user/login")
public String login(@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
<a class="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
package com.bobooy.ems.config;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* @author BoBooY
* @date 2022/9/30 19:50
*/
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
if(session.getAttribute("loginUser") == null) {
request.setAttribute("msg","您没有权限,请先登录");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
} else {
return true;
}
}
}
- 在配置类中注册拦截器MyMvcConfig
//配置拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/","/index.html","/user/login","/css/**","/img/**","/js/**");
}
- 测试