SpringBoot-10-项目实战

SpringBoot-10-项目实战

1. 项目简介

  • 该项目整合了CRUD实现员工管理案例,将MyBatis整合到原项目中,加入了数据库,添加了日期选项控件

环境要求

  • IDEA
  • MySQL
  • Maven
  • 需要熟练掌握MySQL数据库,SpringBoot及MyBatis知识,简单的前端知识;

2. 环境准备

小概念理解:

  • OR映射(ORM,Obeject Releation Mapping):就是将对象与关系数据库进行绑定(或者说是把关系数据表进

  • PO(Persistant Object): 可以看成是与数据库中的表相映射的java对象。最简单的PO就是对应数据库中某个表中的一条记录,多个记录可以用PO的集合。PO中应该不包含任何对数据库的操作。好处就是可以把一条记录作为一个对象处理,可以方便的转为其他对象。

  • VO值对象,通常用于业务层之间的数据传递,与PO一样仅包含数据,根据业务的需要与抽象出的业务对象实现对应或者非对应。

    • VO主要对应界面显示的数据对象。对于一个WEB页面,或者SWT/SWING的一个界面,用一个VO对象对应整个界面的值
    • 个人的理解是:VO是 Controller中携带的ModelAndView 对象
  • DAO(Data Access Object数据访问对象),用于访问数据库,通常与PO结合使用,DAO包含了各种数据库的操作方法RequestParam

    • 通过方法结合PO对数据库进行相关操作,夹在业务层逻辑与数据库资源中间,配合VO,提供数据库的CRUD(增删改查)操作。
  • POJO(Plain Ordinary Java Object简单无规则java对象)是纯粹的传统意义的java对象。就是说在一些Object/Relation Mapping工具中,能够做到维护数据库表记录的persisent object完全是一个符合Java Bean规范的纯Java对象,没有增加别的属性和方法,

    • 即,最基本的Java Bean,只有属性字段及settergetter方法!
  • DTO(Data Transfer Object,数据传输对象)主要用于远程调用等需要大量传输对象的地方。

    • 比如说,我们一张表有100个字段,那么对应的PO就有100个属性。但是我们界面上只要显示10个字段, 客户端用WEB service来获取数据,没有必要把整个PO对象传递到客户端

    • 这时我们就可以用只有这10个属性的DTO来传递结果到客户端,这样也不会暴露服务端表结构.到达客户端以后,如果用这个对象来对应界面显示,那此时它的身份就转为VO。

    • DTO 是一组需要跨进程或网络边界传输的聚合数据的简单容器。它不应该包含业务逻辑,并将其行为限制为诸如内部一致性检查和基本验证之类的活动。注意,不要因实 现这些方法而导致 DTO 依赖于任何新类。在设计数据传输对象时,您有两种主要选择:使用一般集合;或使用显式的 getter 和 setter 方法创建自定义对象

  • BO(Business Object)业务对象,封装业务逻辑的java对象,通过调用DAO方法,结合PO,VO进行业务操作。这个对象可以包括一个或多个其它的对象。

    • 比如一个简历,有教育经历、工作经历、 关系等等。我们可以把教育经历对应一个PO,工作经历对应一个PO, 关系对应一个PO。建立一个对应简历的BO对象处理简历,每个BO包含这些PO。这样处理业务逻辑时,我们就可以针对BO去处理。
      关于BO主要有三种概念 :
      • 只包含业务对象的属性;
      • 只包含业务方法;
      • 两者都包含。

    在实际使用中,认为哪一种概念正确并不重要,关键是实际应用中适合自己项目的需要

  • 如果没有VOPO 的区别,那么数据库表结构的所有字段就一览无余地展示到了前端,给后台安全带来很大的隐患,并且无法在网络传输中剥离冗余信息提高了用户的带宽成本

例子分析:

以一个实例来探讨下POJO 的使用。假设我们有一个面试系统,数据库中存储了很多面试题,通过 web 和 API 提供服务。可能会做如下的设计:
1)数据表:表中的面试题包括编号、题目、选项、答案、创建时间、修改时间;
2)PO:包括题目、选项、答案、创建时间、修改时间;
3)VO:题目、选项、答案、上一题URL、下一题URL;
4)DTO:编号、题目、选项、答案、上一题编号、下一题编号;
5)DAO:数据库增删改查方法;
6)BO:业务基本操作。

  • 可以看到,进行POJO 划分后,我们得到了一个设计良好的架构,各层数据对象的修改完全可以控制在有限的范围内。

2.1 创建案例所使用的数据库

1
2
3
CREATE DATABASE `springboot`;

USE `springboot`;

2.2 创建登录用户数据表

1
2
3
4
5
6
7
8
9
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(10) NOT NULL,
`user_name` varchar(255) NOT NULL COMMENT '用户名',
`password` varchar(255) NOT NULL COMMENT '密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;

INSERT INTO `user` VALUES (1, 'admin', '123456');

2.3 创建部门信息数据库表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(10) NOT NULL,
`department_name` varchar(255) NOT NULL COMMENT '部门名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

BEGIN;
INSERT INTO `department` VALUES (1, '市场部');
INSERT INTO `department` VALUES (2, '技术部');
INSERT INTO `department` VALUES (3, '销售部');
INSERT INTO `department` VALUES (4, '客服部');
INSERT INTO `department` VALUES (5, '公关部');
COMMIT;

2.4 创建存放员工信息的数据库表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`employee_name` varchar(255) NOT NULL COMMENT '员工姓名',
`email` varchar(255) NOT NULL COMMENT '员工邮箱',
`gender` int(2) NOT NULL COMMENT '员工性别',
`department_id` int(10) NOT NULL COMMENT '部门编号',
`date` date NOT NULL COMMENT '入职日期',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

BEGIN;
INSERT INTO `employee` VALUES (1, '张三', 'zhangsan@gmail.com', 0, 1, '2020-02-12');
INSERT INTO `employee` VALUES (2, '李四', 'lisi@qq.com', 1, 2, '2020-02-05');
INSERT INTO `employee` VALUES (3, '王五', 'wangwu@126.com', 0, 3, '2020-02-15');
INSERT INTO `employee` VALUES (4, '赵六', 'zhaoliu@163.com', 1, 4, '2020-02-21');
INSERT INTO `employee` VALUES (5, '田七', 'tianqi@foxmail.com', 0, 3, '2020-02-14');
INSERT INTO `employee` VALUES (10, '王伟', 'wangwei@gmail.com', 1, 3, '2020-02-08');
INSERT INTO `employee` VALUES (11, '张伟', 'zhangwei@gmail.com', 1, 2, '2020-02-11');
INSERT INTO `employee` VALUES (12, '李伟', 'liwei@gmail.com', 1, 3, '2020-02-18');
COMMIT;

2.5 基本环境搭建

  1. 新建Spring项目, 添加Lombok,Spring Web,Thymeleaf,Mybatis,MySQL Driver的支持
  2. 相关的pom依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

2.6 构建基本项目结构

  • com.zhuuu.pojo
  • com.zhuuu.DTO
  • com.zhuuu.mapper
  • com.zhuuu.service
  • com.zhuuu.config

同时application.properties添加mapper映射和数据库连接信息

1
2
3
4
5
6
7
8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.type-aliases-package=com.zhuuu.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true
spring.messages.basename=i18n.login

测试数据库连接:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class SpringbootCrudApplicationTests {

@Autowired
DataSource dataSource;

@Test
public void contextLoads() throws SQLException {
System.out.println("数据源>>>>>>" + dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println("连接>>>>>>>>>" + connection);
System.out.println("连接地址>>>>>" + connection.getMetaData().getURL());
connection.close();
}

}

查看输出结果,数据库配置ok

3. 创建pojo实体类

  • 一共三个实体类,对应于三个角色
  1. 创建User实体类
1
2
3
4
5
6
7
8
9
package com.zhuuu.pojo;
import lombok.Data;

@Data
public class User {
private int id;
private String userName;
private String password;
}
  1. 创建Department实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.zhuuu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
//部门表
public class Department {

private Integer id;
private String departmentName;
}
  1. 创建Employee实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.zhuuu.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;

//员工表
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender; //0:女 1:男

private Department department;
private Date birth;

public Employee(Integer id, String lastName, String email, Integer gender, Department department) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
//默认的创建日期
this.birth = new Date();
}
}

4. 创建Mapper层 :对数据库的操作

文件存放目录:

com.zhuuu.mapper 相关接口

resources/mapper 相关mapper.xml

  • MyBatis默认无需写接口的实现类
  1. 编写UserMapper接口:UserMapper
1
2
3
4
5
6
7
8
9
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface UserMapper {
User selectPasswordByName(@Param("userName") String userName,@Param("password") String password);
}
  1. 编写Mapper对应的UserMapper.xml
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhuuu.mapper.UserMapper">
<select id="selectPasswordByName" resultType="User">
select * from user where user_name = #{userName} and password = #{password}
</select>
</mapper>
  1. 编写DepartmentMapper接口:DepartmentMapper
1
2
3
4
5
6
7
8
9
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;

@Mapper
@Repository
public interface DepartmentMapper {
List<Department> selectAllDepartment();
}
  1. 编写接口对应的Mapper.xml文件:DepaertmentMapper.xml
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhuuu.mapper.DepartmentMapper">
<select id="selectAllDepartment" resultType="Department">
select * from department
</select>
</mapper>
  1. 编写EmployeeMapper接口:EmployeeMapper
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;

@Mapper
@Repository
public interface EmployeeMapper {
//查询全部员工信息
List<EmployeeDTO> selectAllEmployeeDTO();
//根据id查询员工信息
Employee selectEmployeeById(int id);
//添加一个员工信息
int addEmployee(Employee employee);
//修改一个员工信息
int updateEmployee(Employee employee);
//根据id删除员工信息
int deleteEmployee(int id);
}
  1. 编写接口对应的Mapper.xml文件:EmployeeMapper.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhuuu.mapper.EmployeeMapper">

<resultMap id="EmployeeDTO" type="com.zhuuu.dao.EmployeeDTO">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="employee_name" jdbcType="VARCHAR" property="employeeName" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="gender" jdbcType="INTEGER" property="gender" />
<result column="department_name" jdbcType="VARCHAR" property="departmentName" />
<result column="date" jdbcType="DATE" property="date" />
</resultMap>

<select id="selectAllEmployeeDTO" resultMap="EmployeeDao">
select e.id,e.employee_name,e.email,e.gender,d.department_name,e.date
from employee e,department d
where e.department_id = d.id
</select>

<select id="selectEmployeeById" resultType="Employee">
select * from employee where id = #{id}
</select>

<insert id="addEmployee" parameterType="Employee">
insert into employee (id,employee_name,email,gender,department_id,date)
values (#{id},#{employeeName},#{email},#{gender},#{departmentId},#{date})
</insert>

<update id="updateEmployee" parameterType="Employee">
update employee
set employee_name=#{employeeName},email=#{email} ,gender=#{gender} ,department_id=#{departmentId} ,date=#{date}
where id = #{id}
</update>

<delete id="deleteEmployee" parameterType="int">
delete from employee where id = #{id}
</delete>
</mapper>

5. 创建 Service层

  1. EmployeeService接口:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.List;

public interface EmployeeService {
//查询全部员工信息
List<EmployeeDTO> selectAllEmployeeDTO();
//根据id查询员工信息
Employee selectEmployeeById(int id);
//添加一个员工信息
int addEmployee(Employee employee);
//修改一个员工信息
int updateEmployee(Employee employee);
//根据id删除员工信息
int deleteEmployee(int id);
}
  1. EmployeeServiceImpl实现类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

// 将dao层的接口注入就行
@Autowired
private EmployeeMapper employeeMapper;

@Override
public List<EmployeeDTO> selectAllEmployeeDTO() {
return employeeMapper.selectAllEmployeeDTO();
}

@Override
public Employee selectEmployeeById(int id) {
return employeeMapper.selectEmployeeById(id);
}

@Override
public int addEmployee(Employee employee) {
return employeeMapper.addEmployee(employee);
}

@Override
public int updateEmployee(Employee employee) {
return employeeMapper.updateEmployee(employee);
}

@Override
public int deleteEmployee(int id) {
return employeeMapper.deleteEmployee(id);
}
}
  1. DepartmentService接口
1
2
3
4
5
import java.util.List;

public interface DepartmentService {
List<Department> selectAllDepartment();
}
  1. DepartmentImpl实现类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {

// 将dao层的接口注入就行
@Autowired
private DepartmentMapper departmentMapper;

@Override
public List<Department> selectAllDepartment() {
return departmentMapper.selectAllDepartment();
}
}
  1. UserService接口
1
2
3
public interface UserService {
User selectPasswordByName(String userName,String password);
}
  1. UserServiceImpl实现类
1
2
3
4
5
6
7
8
9
10
11
@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserMapper userMapper;

@Override
public User selectPasswordByName(String userName,String password) {
return userMapper.selectPasswordByName(userName,password);
}
}
  1. 测试目前结果是否有误
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  @Autowired
EmployeeService employeeService;

@Test
public void test(){
List<EmployeeDTO> employees = employeeService.selectAllEmployeeDTO();
for (EmployeeDTO employee : employees) {
System.out.println(employee);
}
}
@Test
public void test2(){
Employee employee = employeeService.selectEmployeeById(1);
System.out.println(employee);
//Employee(id=1, employeeName=张三, email=zhangsan@gmail.com, gender=0, departmentId=1, date=2020-02-12)
}

@Test
public void test3(){
Employee employee = new Employee();
employee.setId(6);
employee.setEmployeeName("test");
employee.setEmail("123@qq.com");
employee.setDepartmentId(2);
Date date = new Date(2020-02-02);
employee.setDate(date);
employeeService.addEmployee(employee);
Employee employee1 = employeeService.selectEmployeeById(6);
System.out.println(employee1);
//Employee(id=6, employeeName=test, email=123@qq.com, gender=0, departmentId=2, date=1970-01-01)
}

@Test
public void test4(){
Employee employee = new Employee();
employee.setId(6);
employee.setEmployeeName("test");
employee.setEmail("123@qq.com");
employee.setDepartmentId(3);
Date date = new Date(2020-02-02);
employee.setDate(date);
employeeService.updateEmployee(employee);
Employee employee1 = employeeService.selectEmployeeById(6);
System.out.println(employee1);
//Employee(id=6, employeeName=test, email=123@qq.com, gender=0, departmentId=3, date=1970-01-01)
}

@Test
public void test05(){
employeeService.deleteEmployee(6);
}

@Autowired
private UserService userService;
@Test
public void test06(){
User admin = userService.selectPasswordByName("admin","123456");
System.out.println(admin);
//User(id=1, name=admin, password=123456)
}

@Autowired
private DepartmentService departmentService;
@Test
public void test07(){
List<Department> departments = departmentService.selectAllDepartment();
for (Department department : departments) {
System.out.println(department);
}
}

6. 创建 Controller层

  1. 登陆功能: LoginController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Controller
public class LoginController {

@Autowired
private UserService userService;

// loginController
@RequestMapping("/login")
// @RequestParam(“前端传来的参数”) String username(后端改名后的参数)
public String login(@RequestParam("username")String username,
@RequestParam("password")String password,
HttpSession session,
Model model){
User user = userService.selectPasswordByName(username, password);
if ( user != null){
// 1. 登录成功!
session.setAttribute("username",user.getUserName());
// 2. 防止表单重复提交,我们重定向
return "redirect:/main.html"; // main.html并不是一个页面,而是一个虚假的请求,但此时main.html都可以登录了,所以需要拦截器
}else {
// 3. 登录失败!存放错误信息
model.addAttribute("msg","用户名或密码错误");
return "index";
}
}

// logoutController : 注销功能
@GetMapping("/user/loginOut")
public String loginOut(HttpSession session){
session.invalidate(); // 不用毁了session,失效就行了
return "redirect:/index.html";
}
}
  1. 员工信息Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
@Controller
public class EmploeeController {

// 要员工就注入员工
@Autowired
private EmployeeService employeeService;

// 要部门就注入部门
@Autowired
private DepartmentService departmentService;

//1. 查询所有员工,返回列表页面
@GetMapping("/emp")
public String list(Model model){
Collection<EmployeeDTO> employees = employeeService.selectAllEmployeeDTO();
// 1.1 将结果放在请求中
model.addAttribute("emps",employees);
// 1.2 返回xx页面
return "emp/list.html";
}

//2. 去员工添加页面
@GetMapping("/add")
public String toAdd(Model model){
//查出所有的部门,提供页面信息选择
Collection<Department> departments = departmentService.selectAllDepartment();
// 2.1 结果放在请求中
model.addAttribute("departments",departments);
// 2.2 跳转页面
return "emp/add.html";
}

//3. 员工添加功能,使用post接收
@PostMapping("/add")
public String add(Employee employee){
// 3.1 保存员工信息
employeeService.addEmployee(employee);
// 3.2 回到员工列表页面,可以使用redirect或者forward
return "redirect:/emp";
}

//4. 去 员工修改页面
@GetMapping("/emp/{id}")
public String toUpdateEmp(@PathVariable("id") Integer id, Model model){ // PathVariable 前端传过来的参数,同时实现了restFul风格
//4.1 根据id查出来员工
Employee employee = employeeService.selectEmployeeById(id);
//4.2 将员工信息返回页面
model.addAttribute("emp",employee); // 将数据回显前端
//4.3 查出所有的部门,提供修改选择
Collection<Department> departments = departmentService.selectAllDepartment();
model.addAttribute("departments",departments); // 将数据回显前端
return "emp/update.html";
}

// 5. 修改员工数据
@PostMapping("/updateEmp")
public String updateEmp(Employee employee){
// 5.1 修改员工数据
employeeService.updateEmployee(employee);
// 5.2 回到员工列表页面
return "redirect:/emp";
}

// 6. 删除员工信息
@GetMapping("/delEmp/{id}")
public String deleteEmp(@PathVariable("id")Integer id){
// 6.1 根据id删除员工
employeeService.deleteEmployee(id);
// 6.2 返回xx页面
return "redirect:/emp";
}
}

7. 创建 Config层

7.1 登陆拦截器

  1. 编写Interceptor拦截器配置 :拦截不经过登陆,直接可以访问后台的请求
    • 企业中,目前大量还是这样的代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyHandlerInterceptor implements HandlerInterceptor {
@Override
// 1. 在请求刚拿到就开始拦截
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 1.1 拿到登陆的username
Object username = request.getSession().getAttribute("username");
// 1.2 如果没有登陆,转发到首页,不放行
if (username == null){
request.setAttribute("msg","没有权限");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
// 1.2 之前登录过,放行
return true;
}
}
}
  1. 编写国际化配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.zhuuu.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;

public class MyLocaleResolver implements LocaleResolver {
//解析请求
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取请求中的语言参数
String language = request.getParameter("l");

Locale locale = Locale.getDefault(); //如果没有就使用默认的
//如果请求的链接携带了国际化的参数
if(!StringUtils.isEmpty(language)){
//zh_CN
String[] split = language.split("_");
//国家,地区
locale = new Locale(split[0], split[1]);
}
return locale;
}

@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

}
}

7.2 MVC 配置

  1. 编写WebMvc文件,将上述配置到MvcConfiguration中。(必须要有的MVC总配置)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
//1. 注册拦截器,及拦截请求和要剔除哪些请求!
public void addInterceptors(InterceptorRegistry registry) {
// 1.1 添加拦截器
registry.addInterceptor(new MyHandlerInterceptor())
// 1.2 我们还需要过滤静态资源文件,否则样式显示不出来
.addPathPatterns("/**") // 1.3 所有请求都拦截
.excludePathPatterns("/","/index.html","/login","/css/**","/js/**","/img/**");
// 1.4 哪些请求不能拦截
}

// addViewController : 等价于写了个RequestMapping进行视图跳转,
// 同理的,对于RequestMapping(请求),这个请求并不一定需要存在
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
registry.addViewController("/main.html").setViewName("main");
}

@Bean
public LocaleResolver localeResolver(){
//国际化相关配置
return new MyLocaleResolver();
}
}

8. 前端视图

前端视图结构如下:

8.1 首页

  1. 登陆页index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Signin Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="@{/css/signin.css}" rel="stylesheet">
</head>

<body class="text-center">
<form class="form-signin" th:action="@{/login}">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="">
<!--判断是否显示,使用if, ${}可以使用工具类,可以看thymeleaf的中文文档-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" > [[#{login.remember}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.btn}]]</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm" th:href="@{/index.html(l=zh_CN)}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l=en_US)}">English</a>
</form>
</body>
</html>

8.2 提取公共页面

  1. 公共页/common/commons.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html >
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
<!--后台主页显示登录用户的信息-->
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.username}]]</a>
<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">
<a class="nav-link" href="#" th:href="@{/user/loginOut}">Sign out</a>
</li>
</ul>
</nav>

<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar">
<div class="sidebar-sticky">
<ul class="nav flex-column">
<li class="nav-item">
<a th:class="${active} == 'main.html'?'nav-link active':'nav-link'" th:href="@{/main.html}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
<polyline points="9 22 9 12 15 12 15 22"></polyline>
</svg>
首页 <span class="sr-only">(current)</span>
</a>

<li class="nav-item">
<a th:class="${active} == 'list.html'?'nav-link active':'nav-link'" th:href="@{/emp}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
员工管理
</a>
</li>
</ul>
</div>
</nav>

</html>

8.3 系统主页面

  1. 系统管理页 main.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">

<title>Dashboard Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">

<!-- Custom styles for this template -->
<link th:href="@{/css/dashboard.css}" rel="stylesheet">
<style type="text/css">
/* Chart.js */

@-webkit-keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}

@keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}

.chartjs-render-monitor {
-webkit-animation: chartjs-render-animation 0.001s;
animation: chartjs-render-animation 0.001s;
}
</style>
</head>

<body>
<div th:replace="~{common/commons::topbar}"></div>


<div class="container-fluid">
<div class="row">
<!--引入抽取的topbar-->
<!--模板名 : 会使用thymeleaf的前后缀配置规则进行解析
使用~{模板::标签名}-->
<div th:replace="~{common/commons::sidebar(active='main.html')}"></div>

<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<div class="chartjs-size-monitor" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;">
<div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
<div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div>
</div>
<div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
<div style="position:absolute;width:200%;height:200%;left:0; top:0"></div>
</div>
</div>
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
<h1 class="h2">Dashboard</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group mr-2">
<button class="btn btn-sm btn-outline-secondary">Share</button>
<button class="btn btn-sm btn-outline-secondary">Export</button>
</div>
<button class="btn btn-sm btn-outline-secondary dropdown-toggle">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-calendar"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line></svg>
This week
</button>
</div>
</div>
<canvas class="my-4 chartjs-render-monitor" id="myChart" width="1076" height="454" style="display: block; width: 1076px; height: 454px;"></canvas>
</main>
</div>
</div>

<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js" ></script>
<script type="text/javascript" src="asserts/js/popper.min.js" ></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js" ></script>
</body>
</html>

8.4 员工详情页

  1. 员工详情页 /emp/list.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">

<title>Dashboard Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">

<!-- Custom styles for this template -->
<link th:href="@{/css/dashboard.css}" rel="stylesheet">
<style type="text/css">

@-webkit-keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}

@keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}

.chartjs-render-monitor {
-webkit-animation: chartjs-render-animation 0.001s;
animation: chartjs-render-animation 0.001s;
}
</style>
</head>

<body>
<div th:replace="~{common/commons::topbar}"></div>

<div class="container-fluid">
<div class="row">
<div th:replace="~{common/commons::sidebar(active='list.html')}"></div>

<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h2>员工管理</h2>
<!--添加员工按钮-->
<a class="btn btn-sm btn-primary" th:href="@{/add}">添加</a>

<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>邮箱</th>
<th>性别</th>
<th>部门</th>
<th>入职日期</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="emp:${emps}">
<td th:text="${emp.getId()}"></td>
<td th:text="${emp.getEmployeeName()}"></td>
<td th:text="${emp.getEmail()}"></td>
<td th:text="${emp.getGender() == 0 ? '女':'男'}"></td>
<td th:text="${emp.getDepartmentName()}"></td>
<!--使用时间格式化工具-->
<td th:text="${#dates.format(emp.getDate(),'yyyy-MM-dd')}"></td>
<td >

<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>
<a class="btn btn-sm btn-danger" th:href="@{/delEmp/}+${emp.id}">删除</a>
</td>
</tr>

</tbody>
</table>
</div>
</main>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js"></script>
<script type="text/javascript" src="asserts/js/popper.min.js"></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js"></script>

</body>
</html>

8.5 添加员工页面

  1. 添加员工页 /emp/add.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Dashboard Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="@{/css/dashboard.css}" rel="stylesheet">


<style type="text/css">
/* Chart.js */

@-webkit-keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}

@keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}

.chartjs-render-monitor {
-webkit-animation: chartjs-render-animation 0.001s;
animation: chartjs-render-animation 0.001s;
}
</style>
</head>

<body>
<div th:replace="~{common/commons::topbar}"></div>

<div class="container-fluid">
<div class="row">
<div th:replace="~{common/commons::sidebar(active='list.html')}"></div>

<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h2>添加员工信息</h2>
<form th:action="@{/add}" method="post">
<div class="form-group">
<label for="InputName">姓名</label>
<input name="employeeName" type="text" class="form-control" id="InputName" placeholder="张三" >

</div>
<div class="form-group">
<label for="InputEmail1">邮箱</label>
<input name="email" type="email" class="form-control" id="InputEmail1" placeholder="123@123.com">
</div>
<div class="form-group">
<label >性别</label>
<div class="form-check form-check-inline" >
<input class="form-check-input" type="radio" name="gender" value="1">
<label class="form-check-label"></label>
</div>
<div class="form-check form-check-inline" >
<input class="form-check-input" type="radio" name="gender" value="0">
<label class="form-check-label"></label>
</div>
</div>
<div class="form-group">
<label>部门</label>
<!--提交的是部门的ID-->
<select class="form-control" name="departmentId">
<option>请选择</option>
<option th:each="dept:${departments}" th:text="${dept.departmentName}" th:value="${dept.id}">1</option>
</select>
</div>
<div class="form-group">
<label>入职日期</label>
<input name="date" type="text" class="form-control" id="dateFormat" autocomplete="off">
</div>

<button type="submit" class="btn btn-primary">提交</button>
</form>
</main>
</div>
</div>

<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js"></script>
<script type="text/javascript" src="asserts/js/popper.min.js"></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js"></script>

<!-- 日期组件-->
<script type="text/javascript" src="/laydate/laydate.js"></script>
<!-- 改成你的路径 -->
<script>
//执行一个laydate实例
laydate.render({
elem: '#dateFormat' ,
trigger:'click'//指定元素
});
</script>
</body>

</html>

8.6 修改员工页面

  1. 修改员工页 /emp/add.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">

<title>Dashboard Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">

<!-- Custom styles for this template -->
<link th:href="@{/css/dashboard.css}" rel="stylesheet">
<style type="text/css">
/* Chart.js */

@-webkit-keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}

@keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}

.chartjs-render-monitor {
-webkit-animation: chartjs-render-animation 0.001s;
animation: chartjs-render-animation 0.001s;
}
</style>
</head>

<body>
<div th:replace="~{common/commons::topbar}"></div>

<div class="container-fluid">
<div class="row">
<div th:replace="~{common/commons::sidebar(active='list.html')}"></div>

<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h2>修改员工信息</h2>
<form th:action="@{/updateEmp}" method="post" >
<input name="id" type="hidden" class="form-control" th:value="${emp.id}">
<div class="form-group">
<label>姓名</label>
<input name="employeeName" type="text" class="form-control " th:value="${emp.employeeName}" >
</div>
<div class="form-group">
<label>邮箱</label>
<input name="email" type="email" class="form-control" th:value="${emp.email}">
</div>
<div class="form-group">
<label>性别</label><br/>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="1"
th:checked="${emp.gender==1}">
<label class="form-check-label"></label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="0"
th:checked="${emp.gender==0}">
<label class="form-check-label"></label>
</div>
</div>
<div class="form-group">
<label>部门</label>
<!--提交的是部门的ID-->
<select class="form-control" name="departmentId">
<option th:selected="${dept.id == emp.departmentId}" th:each="dept:${departments}"
th:text="${dept.departmentName}" th:value="${dept.id}">1
</option>
</select>
</div>
<div class="form-group">
<label>时间</label>
<input name="date" type="text" class="form-control" th:value="${#dates.format(emp.date,'yyyy-MM-dd')}" id="dateFormat" autocomplete="off">
</div>
<button type="submit" class="btn btn-primary">修改</button>
</form>

</html>
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信