静态资源链接:https://blog.csdn.net/qq_58233406/article/details/126838809
springboot2.6.11默认的mysql版本为8.0.30,本人mysql用的版本是5.7
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
<scope>runtimescope>
dependency>
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请求
}
}
设置项目编码为UTF-8
编写国际化配置文件
编写配置
login.btn=请登录
login.username=用户名
login.password=密码
login.remember=记住我
login.tip=请登录
login.btn=sign in
login.username=username
login.password=password
login.remember=remember me
login.tip=Please sign in
login.btn=请登录
login.username=用户名
login.password=密码
login.remember=记住我
login.tip=请登录
配置messages路径(注意空格,笔记代码只记录部分关键代码)
#国际化配置
messages:
basename: i18n.login
配置国际化
<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')}">Englisha>
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) {
}
}
@Bean
public LocaleResolver localeResolver() {
return new MyLocaleResolver();
}
registry.addViewController("/index.html").setViewName("index");
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');
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;
}
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;
}
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;
}
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.6version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
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
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;
}
}
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);
}
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>
#配置Mybatis
Mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.bobooy.ems.pojo
public interface UserService {
User getUser(String userName);
}
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);
}
}
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";
}
}
}
registry.addViewController("/main.html").setViewName("dashboard");
<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>
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;
}
}
}
//配置拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/","/index.html","/user/login","/css/**","/img/**","/js/**");
}
DAO层
package com.bobooy.ems.mapper;
import com.bobooy.ems.pojo.Employee;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.Collection;
/**
* @author BoBooY
* @date 2022/9/26 23:23
*/
@Mapper
@Repository
public interface EmployeeMapper {
//查询全体员工信息
public Collection<Employee> getAll();
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bobooy.ems.mapper.EmployeeMapper">
<select id="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>
<resultMap id="EmployeeDepartment" type="Employee">
<result property="id" column="eid"/>
<result property="lastName" column="eName"/>
<result property="email" column="email"/>
<result property="gender" column="gender"/>
<result property="birth" column="birth"/>
<association property="department" javaType="Department">
<result property="id" column="did"/>
<result property="departmentName" column="dName"/>
association>
resultMap>
mapper>
service层
编写EmployeeService
package com.bobooy.ems.service;
import com.bobooy.ems.mapper.EmployeeMapper;
import com.bobooy.ems.pojo.Employee;
import org.springframework.stereotype.Service;
import java.util.Collection;
/**
* @author BoBooY
* @date 2022/9/26 23:44
*/
public interface EmployeeService {
//查询全体员工信息
public Collection<Employee> getAll();
}
package com.bobooy.ems.service;
import com.bobooy.ems.mapper.EmployeeMapper;
import com.bobooy.ems.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
/**
* @author BoBooY
* @date 2022/9/26 23:45
*/
@Service
public class EmployeeServiceImpl implements EmployeeService{
@Override
public Collection<Employee> getAll() {
return employeeMapper.getAll();
}
}
controller层
package com.bobooy.ems.controller;
import com.bobooy.ems.mapper.EmployeeMapper;
import com.bobooy.ems.pojo.Employee;
import com.bobooy.ems.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collection;
/**
* @author BoBooY
* @date 2022/9/26 23:20
*/
@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@RequestMapping("/emps")
public String list(Model model) {
Collection<Employee> employees = employeeService.getAll();
model.addAttribute("emps",employees);
return "emp/list";
}
}
测试
DAO层
package com.bobooy.ems.mapper;
import com.bobooy.ems.pojo.Department;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.Collection;
/**
* @author BoBooY
* @date 2022/9/27 0:01
*/
@Mapper
@Repository
public interface DepartmentMapper {
//获取所有部门的信息
Collection<Department> getDepartments();
// 通过ID查询部门
Department getDepartmentById(Integer id);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bobooy.ems.mapper.DepartmentMapper">
<select id="getDepartments" resultType="Department">
select * from department
select>
<select id="getDepartmentById" resultType="Department" parameterType="Integer">
select * from department where id = #{id}
select>
mapper>
configuration:
map-underscore-to-camel-case: true #开启驼峰命名
Service层
package com.bobooy.ems.service;
import com.bobooy.ems.pojo.Department;
import java.util.Collection;
/**
* @author BoBooY
* @date 2022/10/2 10:31
*/
public interface DepartmentService {
//获取所有部门的信息
Collection<Department> getDepartments();
// 通过ID查询部门
Department getDepartmentById(Integer id);
}
package com.bobooy.ems.service;
import com.bobooy.ems.mapper.DepartmentMapper;
import com.bobooy.ems.pojo.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
/**
* @author BoBooY
* @date 2022/10/2 10:32
*/
@Service
public class DepartmentServiceImpl implements DepartmentService{
@Autowired
private DepartmentMapper departmentMapper;
@Override
public Collection<Department> getDepartments() {
return departmentMapper.getDepartments();
}
@Override
public Department getDepartmentById(Integer id) {
return departmentMapper.getDepartmentById(id);
}
}
Controller层
@Autowired
private DepartmentService departmentService;
@GetMapping("/add")
public String add(Model model) {
Collection<Department> departments = departmentService.getDepartments();
model.addAttribute("depts",departments);
System.out.println(departments);
return "emp/add";
}
测试
DAO层
//添加员工
public int save(Employee employee);
<insert id="save" parameterType="Employee">
insert into employee(`last_name`, `email`, `gender`, `department`, `birth`)
values (#{lastName}, #{email}, #{gender}, #{department.id}, #{birth})
insert>
service层
//添加员工
public int save(Employee employee);
@Override
public int save(Employee employee) {
return employeeMapper.save(employee);
}
controller层
//添加员工
@RequestMapping("/addEmp")
public String addEmp(Employee employee) {
int save = employeeService.save(employee);
if(save > 0) {
System.out.println("添加成功!");
} else {
System.out.println("添加失败!");
}
return "redirect:/emps";
}
设置日期格式
#日期格式配置
mvc:
format:
date: yyyy-MM-dd HH:mm
测试:添加员工
成功!
Dao层
//修改员工
public int updateEmployee(Employee employee);
// 通过ID查询员工
public Employee getEmployee(Integer id);
<select id="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>
<update id="updateEmployee" parameterType="Employee">
update employee set `last_name`=#{lastName},`email`=#{email},`gender`=#{gender},`department`=#{department.id},`birth`=#{birth} where `id` = #{id}
update>
service层
// 通过ID查询员工
public Employee getEmployee(Integer id);
//修改员工
public int updateEmployee(Employee employee);
@Override
public Employee getEmployee(Integer id) {
return employeeMapper.getEmployee(id);
}
@Override
public int updateEmployee(Employee employee) {
return employeeMapper.updateEmployee(employee);
}
Controller层
//跳转修改页面
@GetMapping("/update/{id}")
public String update(@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")
public String update(Employee employee) {
int update = employeeService.updateEmployee(employee);
if(update > 0) {
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
return "redirect:/emps";
}
测试:修改id为 1012 的员工部门为 后勤部 性别为男
成功!
Dao层
// 删除员工
public int delete(Integer id);
<delete id="delete" parameterType="int">
delete from employee where `id` = #{id}
delete>
service层
// 删除员工
public int delete(Integer id);
@Override
public int delete(Integer id) {
return employeeMapper.delete(id);
}
controller层
//删除员工
@RequestMapping("/delete/{id}")
public String delete(@PathVariable("id") int id) {
int delete = employeeService.delete(id);
if(delete > 0)
System.out.println("删除成功!");
else {
System.out.println("删除失败!");
}
return "redirect:/emps";
}
测试:删除id为1011的员工
//退出登录
@RequestMapping("/logout")
public String logout(HttpSession session) {
session.invalidate(); //使当前session失效
return "redirect:/index.html";
}
项目成功搭建完成!