SpringMVC-SSM整合
蒲公英 2022-01-01 ItCastCourseSpringMVC
- 掌握SSM整合流程
- 能够编写SSM整合功能模块类
- 能够使用Result统一表现层响应结果
- 能够编写异常处理器进行项目异常的处理
- 能够完成SSM整合前端页面发送请求实现增删改查等操作
- 能够编写、配置拦截器
# SSM整合(重点)
# SSM整合配置
# SSM整合流程
- 创建工程
- SSM整合
- Spring
SpringConfig
- MyBatis
MyBatisConfig
DruidConfig
- druid.properties
- SpringMVC
SpringMvcConfig
ServletConfig
- Spring
- 功能模块
- 表和实体类
- dao/mapper(接口+自动代理)
- service(接口+实现类)
- 业务层接口测试整合JUnit
- controller
- 表现层接口测试(PostMan)
# SSM整合配置
- 创建webapp工程,引入依赖和插件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>springmvc-09-ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!--Servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<!-- mysql 驱动坐标 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- druid 依赖坐标 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- Spring整合MyBatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<!-- spring 整合junit -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
</dependencies>
</project>
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
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
Spring整合MyBatis
- 创建数据库和数据表
-- 创建ssm_db数据库 CREATE DATABASE IF NOT EXISTS ssm_db CHARACTER SET utf8; -- 使用ssm_db数据库 USE ssm_db; -- 创建tbl_book表 CREATE TABLE tbl_book( id INT PRIMARY KEY AUTO_INCREMENT, -- 图书编号 TYPE VARCHAR(100), -- 图书类型 NAME VARCHAR(100), -- 图书名称 description VARCHAR(100) -- 图书描述 ); -- 添加初始化数据 INSERT INTO tbl_book VALUES(NULL,'计算机理论','Spring实战 第5版','Spring入门经典教材,深入理解Spring原理技术内幕'); INSERT INTO tbl_book VALUES(NULL,'计算机理论','Spring 5核心原理与30个类手写实战','十年沉淀之作,手写Spring精华思想'); INSERT INTO tbl_book VALUES(NULL,'计算机理论','Spring 5设计模式','深入Spring源码剖析,Spring源码蕴含的10大设计模式'); INSERT INTO tbl_book VALUES(NULL,'市场营销','直播就该这么做:主播高效沟通实战指南','李子柒、李佳琦、薇娅成长为网红的秘密都在书中'); INSERT INTO tbl_book VALUES(NULL,'市场营销','直播销讲实战一本通','和秋叶一起学系列网络营销书籍'); INSERT INTO tbl_book VALUES(NULL,'市场营销','直播带货:淘宝、天猫直播从新手到高手','一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20- 创建duird.properties属性配置文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm_db jdbc.username=root jdbc.password=1234
1
2
3
4- 创建
DruidConfig
配置类
package com.itheima.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; @PropertySource("classpath:druid.properties") public class DruidConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; // 配置Druid数据库连接池 @Bean public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } // Spring事务管理需要的平台事务管理器对象 @Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(); transactionManager.setDataSource(dataSource); return transactionManager; } }
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
46MyBatisConfig
配置类
package com.itheima.config; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.context.annotation.Bean; import javax.sql.DataSource; public class MyBatisConfig { @Bean public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setTypeAliasesPackage("com.itheima.domain"); return factoryBean; } @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer msc = new MapperScannerConfigurer(); msc.setBasePackage("com.itheima.mapper"); return msc; } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25SpringConfig
配置类
package com.itheima.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @ComponentScan("com.itheima.service") @Import({DruidConfig.class, MyBatisConfig.class}) @EnableTransactionManagement // 开启Spring事务管理 public class SpringConfig { }
1
2
3
4
5
6
7
8
9
10
11
12
13
14Spring整合SpringMVC
SpringMvcConfig
配置类
package com.itheima.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @ComponentScan("com.itheima.controller") @EnableWebMvc public class SpringMvcConfig { }
1
2
3
4
5
6
7
8
9
10
11ServletConfig
配置类,加载SpringMvcConfig
和SpringConfig
配置类
package com.itheima.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{SpringMvcConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 功能模块开发
# 数据层开发(BookDao)
Book
实体类
package com.itheima.domain;
/**
* 图书实体模型
* @author sunyy
* @version 1.0
* @since 2022.1.9
*/
public class Book {
/**
* 主键
*/
private Integer id;
/**
* 类型
*/
private String type;
/**
* 图书名称
*/
private String name;
/**
* 图书描述
*/
private String description;
public Book() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", type='" + type + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
}
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
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
BookMapper
代理接口
package com.itheima.mapper;
import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 图书持久层代理接口
* @author sunyy
* @version 1.0
* @since 2022.1.9
*/
public interface BookMapper {
/**
* 添加图书
* @param book
* @return
*/
int save(Book book);
/**
* 修改图书
* @param book
* @return
*/
int update(Book book);
/**
* 根据id删除图书
* @param id
* @return
*/
int deleteById(@Param("id") Integer id);
/**
* 根据id查询图书
* @param id
* @return
*/
Book getById(@Param("id") Integer id);
/**
* 查询所有图书
* @return
*/
List<Book> getAll();
}
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
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
BookMapper.xml
映射文件
<?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.itheima.mapper.BookMapper">
<resultMap id="BookMap" type="com.itheima.domain.Book">
<id column="id" property="id" />
<result column="type" property="type" />
<result column="name" property="name" />
<result column="description" property="description" />
</resultMap>
<sql id="BookColumns">
id, type, name, description
</sql>
<insert id="save" parameterType="Book">
insert into tbl_book(type, name, description) values(#{type}, #{name}, #{description})
</insert>
<update id="update" parameterType="Book">
update tbl_book
<set>
<if test="type != null and type != ''">
type = #{type},
</if>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="description != null and description != ''">
description = #{description},
</if>
</set>
where id = #{id}
</update>
<delete id="deleteById">
delete from tbl_book where id = #{id}
</delete>
<select id="getById" resultMap="BookMap">
select
<include refid="BookColumns" />
from tbl_book
where id = #{id}
</select>
<select id="getAll" resultMap="BookMap">
select
<include refid="BookColumns" />
from tbl_book
</select>
</mapper>
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
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
# 业务层开发(BookService/BookServiceImpl)
BookService
业务层接口
package com.itheima.service;
import com.itheima.domain.Book;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Book业务层接口
* @author sunyy
* @version 1.0
* @since 2022.1.9
*/
@Transactional // 表示所有方法进行事务管理
public interface BookService {
/**
* 保存图书
* @param book
* @return
*/
boolean save(Book book);
/**
* 修改图书
* @param book
* @return
*/
boolean update(Book book);
/**
* 根据id删除图书
* @param id
* @return
*/
boolean deleteById(Integer id);
/**
* 根据id获取图书信息
* @param id
* @return
*/
Book getById(Integer id);
/**
* 查询全部图书信息
* @return
*/
List<Book> getAll();
}
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
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
BookServiceImpl
业务层实现类
package com.itheima.service.impl;
import com.itheima.domain.Book;
import com.itheima.mapper.BookMapper;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 图书业务层实现类
* @author sunyy
* @version 1.0
* @since 2022.1.9
*/
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
@Override
public boolean save(Book book) {
int count = bookMapper.save(book);
return count > 0;
}
@Override
public boolean update(Book book) {
int count = bookMapper.update(book);
return count > 0;
}
@Override
public boolean deleteById(Integer id) {
int count = bookMapper.deleteById(id);
return count > 0;
}
@Override
public Book getById(Integer id) {
return bookMapper.getById(id);
}
@Override
public List<Book> getAll() {
return bookMapper.getAll();
}
}
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
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
# 表现层开发(BookController)
package com.itheima.controller;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 图书表现层控制器
*/
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
/**
* 保存图书
* @param book
* @return
*/
@PostMapping
public boolean save(@RequestBody Book book) {
return bookService.save(book);
}
/**
* 修改图书
* @param book
* @return
*/
@PutMapping
public boolean update(@RequestBody Book book) {
return bookService.update(book);
}
/**
* 根据id删除
* @param id
* @return
*/
@DeleteMapping("/{id}")
public boolean delete(@PathVariable("id") Integer id) {
return bookService.deleteById(id);
}
/**
* 根据id查询图书详情
* @param id
* @return
*/
@GetMapping("/{id}")
public Book getById(@PathVariable Integer id) {
return bookService.getById(id);
}
/**
* 查询所有图书信息
* @return
*/
@GetMapping
public List<Book> getAll() {
return bookService.getAll();
}
}
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
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
# 接口测试
# Spring整合Junit测试业务层方法
package com.itheima.service;
import com.itheima.config.SpringConfig;
import com.itheima.domain.Book;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
* 使用Junit测试BookService业务层方法
* @author sunyy
* @version 1.0
* @since 2022.1.9
*/
// 使用Spring整合Junit专用类加载器
@RunWith(SpringJUnit4ClassRunner.class)
// 使用配置类初始化容器
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testGetById() {
Book book = bookService.getById(1);
Assert.assertTrue(1 == book.getId());
}
@Test
public void testGetAll() {
List<Book> all = bookService.getAll();
Assert.assertNotNull(all);
}
}
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
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
# PostMan测试表现层接口
# 表现层数据封装(重点)
# 表现层响应数据问题
通过上面BookController
代码我们可以看到,表现层增删改查方法返回的数据五花八门,有返回true
或者false
的,还有返回一个JSON对象或者JSON数组的,这里就出现了三种格式的响应结果,极其不利于前端进行解析。
因此,为了方便前、后台开发人员联调,我们必须统一后台响应结果的格式。怎么做?
# 定义Result类封装响应结果
- 创建
Result
类封装响应结果
package com.itheima.controller;
/**
* 封装响应结果POJO类
* @author sunyy
* @version 1.0
* @since 2023.1.10
*/
public class Result {
// 描述统一格式中的数据
private Object data;
// 描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功或失败
private Integer code;
// 描述统一格式中的消息,可选属性
private String msg;
public Result() {
}
public Result(Integer code, Object data) {
this.data = data;
this.code = code;
}
public Result(Integer code, Object data, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "Result{" +
"data=" + data +
", code=" + code +
", msg='" + msg + '\'' +
'}';
}
}
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
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
注意
Result
类中的字段并不是固定的,可以根据需要自行增减
- 创建
Code
常量类封装响应状态码
package com.itheima.controller;
/**
* Code接口封装响应状态码
* @author sunyy
* @version 1.0
* @since 2023.1.10
*/
public interface Code {
// 保存成功
Integer SAVE_OK = 20011;
// 删除成功
Integer DELETE_OK = 20021;
// 修改成功
Integer UPDATE_OK = 20031;
// 查询成功
Integer GET_OK = 20041;
// 保存失败
Integer SAVE_ERR = 20010;
// 删除失败
Integer DELETE_ERR = 20020;
// 修改失败
Integer UPDATE_ERR = 20030;
// 查询失败
Integer GET_ERR = 20040;
}
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
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
注意
Code
中的常量也不是固定的,可以根据需要自行增减。
# 表现层数据封装返回Result对象
package com.itheima.controller;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 图书表现层控制器
*/
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
/**
* 保存图书
* @param book
* @return
*/
@PostMapping
public Result save(@RequestBody Book book) {
boolean flag = bookService.save(book);
return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
}
/**
* 修改图书
* @param book
* @return
*/
@PutMapping
public Result update(@RequestBody Book book) {
boolean flag = bookService.update(book);
return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
}
/**
* 根据id删除
* @param id
* @return
*/
@DeleteMapping("/{id}")
public Result delete(@PathVariable("id") Integer id) {
boolean flag = bookService.deleteById(id);
return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
}
/**
* 根据id查询图书详情
* @param id
* @return
*/
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
Book book = bookService.getById(id);
Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
String msg = book != null ? "" : "查询数据失败,请重试!";
return new Result(code, book, msg);
}
/**
* 查询所有图书信息
* @return
*/
@GetMapping
public Result getAll() {
List<Book> books = bookService.getAll();
Integer code = books != null ? Code.GET_OK : Code.GET_ERR;
String msg = books != null ? "" : "查询数据失败,请重试!";
return new Result(code, books, msg);
}
}
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
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
# 异常处理器(理解)
# 异常介绍
程序开发过程中不可避免的会出现异常,而且项目各个层级都可能会出现异常,在实际项目中,我们肯定不能染用户蛋刀这样的页面数据:
出现异常现象的常见位置与常见诱因如下:
- 框架内部抛出的异常:因使用不合规导致
- 数据层抛出异常:因外部服务器故障导致(例如:服务器访问超时)
- 业务层抛出异常:因业务逻辑书写错误导致(例如:遍历业务书写错误,导致索引下标越界等)
- 表现层抛出异常:因数据收集、校验等规则导致(例如:不匹配的数据类型转换导致异常)
- 工具类抛出异常:因工具类书写不严谨不够健壮导致(例如:必要的资源释放未释放等)
# 异常处理器
- 编写异常处理器
package com.itheima.controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 异常处理器
* @author sunyy
* @version 1.0
* @since 2023.1.10
*/
@RestControllerAdvice
public class ProjectExceptionAdvice {
/**
* 统一处理所有的Exception异常
* @param ex
* @return
*/
@ExceptionHandler(Exception.class)
public Result doOtherException(Exception ex) {
return new Result(666, null);
}
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
使用异常处理器之后的效果如下:
# 知识点13:@RestControllerAdvice注解
名称 | @RestControllerAdvice |
---|---|
类型 | 类注解 |
位置 | REST风格开发的控制器增强类定义上方 |
作用 | 为REST风格开发的控制器类做增强 |
说明 | 此注解自带@ResponseBody 注解与@Component 注解,并具备对应的功能 |
# 知识点14:@ExceptionHandler注解
名称 | @ExceptionHandler |
---|---|
类型 | 方法注解 |
位置 | 专用于异常处理的控制器方法上方 |
作用 | 设置指定异常的处理方案,功能等同于控制器方法出现异常后终止原始控制器方法的执行,转入当前注解方法执行 |
说明 | 此类方法可以根据处理的异常不同,制作多个方法分别处理对应的异常 |
# 项目异常处理方案(理解)
# 项目异常分类
- 业务异常(BusinessException)
- 规范的用户行为产生的异常
- 不规范的用户行为操作产生的异常
- 系统异常(SystemException)
- 项目运行过程中可预计且无法避免的异常
- 其他异常(Exception)
- 编程人员未预期的异常
# 项目异常处理方案
- 业务异常(BusinessException)
- 发送对应消息传递给用户,提醒规范操作
- 系统异常(SystemException)
- 发送固定消息传递给用户,安抚用户
- 发送特定消息给运维人员,提醒维护
- 记录日志
- 其他异常
- 发送固定消息给用户,安抚用户
- 发送特定消息给开发者,提醒维护并纳入预期范围内
- 记录日志
# 项目异常处理代码实现
# 根据异常分类创建自定义异常类
- 自定义项目系统级异常
package com.itheima.exception;
/**
* 自定义系统级异常,可预计不可避免的异常
* @author sunyy
* @version 1.0
* @since 2023.1.10
*/
public class SystemException extends RuntimeException {
/**
* 异常代码
*/
private Integer code;
public SystemException(Integer code, String message) {
super(message);
this.code = code;
}
public SystemException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
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
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.itheima.exception;
/**
* 自定义项目业务级异常
* @author sunyy
* @version 1.0
* @since 2023.1.10
*/
public class BusinessException extends RuntimeException {
/**
* 异常代码
*/
private Integer code;
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(Integer code,String message,Throwable cause) {
super(message, cause);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
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
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
# 自定义异常编码(Code中持续补充)
package com.itheima.controller;
/**
* Code接口封装响应状态码
* @author sunyy
* @version 1.0
* @since 2023.1.10
*/
public interface Code {
// 之前定义的状态码省略未写,下面是新补充的异常状态码
// 当然也可以根据实际需要自己继续补充
// 系统级异常
Integer SYSTEM_ERR = 50001;
// 超时异常
Integer SYSTEM_TIMEOUT_ERR = 50002;
// 位置异常
Integer SYSTEM_UNKNOW_ERR = 59999;
// 业务级异常
Integer BUSINESS_ERR = 60002;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 触发自定义异常
package com.itheima.service.impl;
import com.itheima.controller.Code;
import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.BookMapper;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 图书业务层实现类
* @author sunyy
* @version 1.0
* @since 2022.1.9
*/
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
// 在getById业务层方法中演示触发异常,其他方法省略未写
@Override
public Book getById(Integer id) {
// 模拟业务异常,包装成自定义业务异常
if (id < 0) {
throw new BusinessException(Code.BUSINESS_ERR, "请不要使用你的技术挑战我的耐心!");
}
return bookMapper.getById(id);
}
}
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
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
# 在异常通知类中拦截并处理异常
package com.itheima.controller;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 异常处理器
* @author sunyy
* @version 1.0
* @since 2023.1.10
*/
@RestControllerAdvice // 用于标识当前类为REST风格对应的异常处理器
public class ProjectExceptionAdvice {
// @ExceptionHandler用于设置当前处理器类方法抛出的异常类型
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex) {
// 记录日志
// 发送消息给运维
// 发送右键给开发人员, ex对象发送给开发人员
return new Result(ex.getCode(), null , ex.getMessage());
}
@ExceptionHandler(BusinessException.class)
public Result doBusinessException(BusinessException ex) {
return new Result(ex.getCode(), null, ex.getMessage());
}
/**
* 统一处理所有的Exception异常
* 除自定义异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
* @param ex
* @return
*/
@ExceptionHandler(Exception.class)
public Result doOtherException(Exception ex) {
// 记录日志
// 发送消息给运维
// 发送邮件给开发人员, ex对象发送给开发人员
return new Result(Code.SYSTEM_UNKNOW_ERR, null, "系统繁忙,请稍后再试!");
}
}
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
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
测试验证:在PostMan中发送请求http://localhost/books/-1
,传递路径参数-1
,得到如下结果
# SSM整合页面开发(重点)
# 准备工作
为了确保静态资源能够被访问,需要设置静态资源过滤
package com.itheima.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* 静态资源过滤处理
* @author sunyy
* @version 1.0
* @since 2023.1.10
*/
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan({"com.itheima.controller", "com.itheima.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 列表查询功能
//列表
getAll() {
//发送ajax请求
axios.get("/books").then((res)=>{
this.dataList = res.data.data;
});
},
1
2
3
4
5
6
7
2
3
4
5
6
7
# 添加功能
//弹出添加窗口
handleCreate() {
this.dialogFormVisible = true;
this.resetForm();
},
//重置表单
resetForm() {
this.formData = {};
},
//添加
handleAdd () {
//发送ajax请求
axios.post("/books",this.formData).then((res)=>{
console.log(res.data);
//如果操作成功,关闭弹层,显示数据
if(res.data.code == 20011){
this.dialogFormVisible = false;
this.$message.success("添加成功");
}else if(res.data.code == 20010){
this.$message.error("添加失败");
}else{
this.$message.error(res.data.msg);
}
}).finally(()=>{
this.getAll();
});
},
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
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
# 修改功能
//弹出编辑窗口
handleUpdate(row) {
// console.log(row); //row.id 查询条件
//查询数据,根据id查询
axios.get("/books/"+row.id).then((res)=>{
// console.log(res.data.data);
if(res.data.code == 20041){
//展示弹层,加载数据
this.formData = res.data.data;
this.dialogFormVisible4Edit = true;
}else{
this.$message.error(res.data.msg);
}
});
},
//编辑
handleEdit() {
//发送ajax请求
axios.put("/books",this.formData).then((res)=>{
//如果操作成功,关闭弹层,显示数据
if(res.data.code == 20031){
this.dialogFormVisible4Edit = false;
this.$message.success("修改成功");
}else if(res.data.code == 20030){
this.$message.error("修改失败");
}else{
this.$message.error(res.data.msg);
}
}).finally(()=>{
this.getAll();
});
},
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
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
# 删除功能
// 删除
handleDelete(row) {
//1.弹出提示框
this.$confirm("此操作永久删除当前数据,是否继续?","提示",{
type:'info'
}).then(()=>{
//2.做删除业务
axios.delete("/books/"+row.id).then((res)=>{
if(res.data.code == 20021){
this.$message.success("删除成功");
}else{
this.$message.error("删除失败");
}
}).finally(()=>{
this.getAll();
});
}).catch(()=>{
//3.取消删除
this.$message.info("取消删除操作");
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 拦截器(理解)
# 拦截器简介
# 拦截器概念和作用
- **拦截器(Interceptor)**是一种动态拦截方法调用机制,在SpringMVC中动态拦截控制器方法的执行
- 作用:
- 在指定的方法调用前后执行预先设定的代码
- 阻止原始方法的执行
- 总结:增强原始控制器方法
- 核心原理:AOP思想
# 拦截器和过滤器的区别
- 归属不同:
Filter
属于Servlet技术,Interceptor
属于SpringMVC技术 - 拦截内容不同:
Filter
对所有访问进行增强,Interceptor
仅针对SpringMVC的访问进行增强
# 拦截器入门案例
- 基于Maven骨架创建模块
- 引入SpringMVC、Servlet、jackson等依赖坐标
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>springmvc-10-interceptor</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!--Servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
</project>
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
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
- 创建配置类
package com.itheima.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
/**
* Post请求中文乱码处理
* @return
*/
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
return new Filter[]{filter};
}
}
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
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
package com.itheima.config;
import com.itheima.controller.interceptor.ProjectInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
public class SpringMvcConfig {
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- 创建控制器类
package com.itheima.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping
public String getAll() {
System.out.println("book controller getAll ...");
return "{'module': 'book controller getAll'}";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- 定义拦截器
package com.itheima.controller.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 拦截器类
* @author sunyy
* @version 1.0
* @since 2023.1.10
*/
// 当前类必须受Spring容器管理
// 定义拦截器类,实现HandlerInterceptor接口
@Component
public class ProjectInterceptor implements HandlerInterceptor {
/**
* 元素方法调用前执行的内容
* 返回值类型可以拦截控制器方法的执行,true表示放行,false表示终止
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle ... ");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
System.out.println("postHandle ... ");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("afterCompletion ... ");
}
}
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
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
配置加载拦截器,有两种方式
- 方式一:
package com.itheima.config; import com.itheima.controller.interceptor.ProjectInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /** * 静态资源过滤处理 以及 拦截器注册 * @author sunyy * @version 1.0 * @since 2023.1.10 */ // 方式一:继承WebMvcConfigurationSupport @Configuration public class SpringMvcSupport extends WebMvcConfigurationSupport { @Autowired private ProjectInterceptor projectInterceptor; @Override protected void addInterceptors(InterceptorRegistry registry) { // 配置拦截器 registry.addInterceptor(projectInterceptor).addPathPatterns("/books", "/books/*"); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/pages/**").addResourceLocations("/pages/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/"); } }
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
36package com.itheima.config; import com.itheima.controller.interceptor.ProjectInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration // 方式一: @ComponentScan({"com.itheima.controller", "com.itheima.config"}) @EnableWebMvc public class SpringMvcConfig implements WebMvcConfigurer { }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17- 方式二:
package com.itheima.config; import com.itheima.controller.interceptor.ProjectInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration // 方式一: // @ComponentScan({"com.itheima.controller", "com.itheima.config"}) @ComponentScan({"com.itheima.controller"}) @EnableWebMvc // 方式二:实现WebMvcConfigurer接口可以简化开发,但是有一定的侵入性 public class SpringMvcConfig implements WebMvcConfigurer { @Autowired private ProjectInterceptor projectInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { // 配置拦截器 registry.addInterceptor(projectInterceptor).addPathPatterns("/books", "/books/*"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/pages/**").addResourceLocations("/pages/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/"); } }
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
拦截器流程分析
# 拦截器参数
# 前置处理
/**
* 元素方法调用前执行的内容
* 返回值类型可以拦截控制器方法的执行,true表示放行,false表示终止
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle ... ");
return true;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
- 参数
request
: 请求对象response
: 响应对象handler
: 被调用的处理器对象,本质上是一个方法对象,对反射技术中的Method
对象进行了再封装
- 返回值:
false
--被拦截的处理器方法将不会执行
# 后置处理
// 原始方法调用后执行的内容
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
System.out.println("postHandle ... ");
}
1
2
3
4
5
6
2
3
4
5
6
- 参数
modelAndView
:如果处理器执行完成具有返回结果,可以读取到对应的数据与页面信息,并进行页面跳转
注意
如果处理器方法出现了异常,该方法不会执行
# 完成后处理
// 原始方法调用完成后执行的内容,控制器方法出异常也会执行
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("afterCompletion ... ");
}
1
2
3
4
5
6
2
3
4
5
6
- 参数
ex
:如果处理器方法执行过程中出现异常对象,可以针对该异常进行单独处理
注意
无论处理器方法内部是否会出现异常,该方法都会执行,但前提必须是preHandle
方法返回true
# 拦截器链配置
# 多个拦截器的配置
- 定义第二个拦截器
package com.itheima.controller.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 拦截器类
* @author sunyy
* @version 1.0
* @since 2023.1.10
*/
// 当前类必须受Spring容器管理
// 定义拦截器类,实现HandlerInterceptor接口
@Component
public class ProjectInterceptor2 implements HandlerInterceptor {
/**
* 元素方法调用前执行的内容
* 返回值类型可以拦截控制器方法的执行,true表示放行,false表示终止
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle ... 222");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
System.out.println("postHandle ... 222");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("afterCompletion ... 222");
}
}
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
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
- 配置第二个拦截器生效
package com.itheima.config;
import com.itheima.controller.interceptor.ProjectInterceptor;
import com.itheima.controller.interceptor.ProjectInterceptor2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
// 方式一:
// @ComponentScan({"com.itheima.controller", "com.itheima.config"})
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
// 方式二:实现WebMvcConfigurer接口可以简化开发,但是有一定的侵入性
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private ProjectInterceptor projectInterceptor;
@Autowired
private ProjectInterceptor2 projectInterceptor2;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 配置拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books", "/books/*");
registry.addInterceptor(projectInterceptor2).addPathPatterns("/books", "/books/*");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
}
}
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
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
# 多个拦截器工作流程分析
- 当配置多个拦截器时,会形成拦截器链
- 拦截器链的运行顺序按照拦截器添加顺序为准
- 当拦截器中出现原始处理器的拦截,后面的拦截器均终止运行
- 当拦截器运行中断,进运行配置在前面的拦截器的
afterCompletion
操作