SpringMVC_day02

今日内容

  • 完成SSM的整合开发
  • 能够理解并实现统一结果封装与统一异常处理
  • 能够完成前后台功能整合开发
  • 掌握拦截器的编写

1,SSM整合

前面我们已经把MybatisSpringSpringMVC三个框架进行了学习,今天主要的内容就是把这三个框架整合在一起完成我们的业务功能开发,具体如何来整合,我们一步步来学习。

1.1 流程分析

(1) 创建工程

  • 创建一个Maven的web工程
  • pom.xml添加SSM需要的依赖jar包
  • 编写Web项目的入口配置类,实现AbstractAnnotationConfigDispatcherServletInitializer重写以下方法

    • getRootConfigClasses() :返回Spring的配置类->需要SpringConfig配置类
    • getServletConfigClasses() :返回SpringMVC的配置类->需要SpringMvcConfig配置类
    • getServletMappings() : 设置SpringMVC请求拦截路径规则
    • getServletFilters() :设置过滤器,解决POST请求中文乱码问题

(2)SSM整合[重点是各个配置的编写]

  • SpringConfig

    • 标识该类为配置类 @Configuration
    • 扫描Service所在的包 @ComponentScan
    • 在Service层要管理事务 @EnableTransactionManagement
    • 读取外部的properties配置文件 @PropertySource
    • 整合Mybatis需要引入Mybatis相关配置类 @Import

      • 第三方数据源配置类 JdbcConfig

        • 构建DataSource数据源,DruidDataSouroce,需要注入数据库连接四要素, @Bean @Value
        • 构建平台事务管理器,DataSourceTransactionManager,@Bean
      • Mybatis配置类 MybatisConfig

        • 构建SqlSessionFactoryBean并设置别名扫描与数据源,@Bean
        • 构建MapperScannerConfigurer并设置DAO层的包扫描
  • SpringMvcConfig

(3)功能模块[与具体的业务模块有关]

1.2 整合配置

掌握上述的知识点后,接下来,我们就可以按照上述的步骤一步步的来完成SSM的整合。

步骤1:创建Maven的web项目

可以使用Maven的骨架创建

😧 SpringMVC_day02 - 图1

步骤2:添加依赖

pom.xml添加SSM所需要的依赖jar包

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.itheima</groupId>
  6. <artifactId>springmvc_08_ssm</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. <packaging>war</packaging>
  9. <dependencies>
  10. <dependency>
  11. <groupId>org.springframework</groupId>
  12. <artifactId>spring-webmvc</artifactId>
  13. <version>5.2.10.RELEASE</version>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.springframework</groupId>
  17. <artifactId>spring-jdbc</artifactId>
  18. <version>5.2.10.RELEASE</version>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework</groupId>
  22. <artifactId>spring-test</artifactId>
  23. <version>5.2.10.RELEASE</version>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.mybatis</groupId>
  27. <artifactId>mybatis</artifactId>
  28. <version>3.5.6</version>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.mybatis</groupId>
  32. <artifactId>mybatis-spring</artifactId>
  33. <version>1.3.0</version>
  34. </dependency>
  35. <dependency>
  36. <groupId>mysql</groupId>
  37. <artifactId>mysql-connector-java</artifactId>
  38. <version>5.1.47</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>com.alibaba</groupId>
  42. <artifactId>druid</artifactId>
  43. <version>1.1.16</version>
  44. </dependency>
  45. <dependency>
  46. <groupId>junit</groupId>
  47. <artifactId>junit</artifactId>
  48. <version>4.12</version>
  49. <scope>test</scope>
  50. </dependency>
  51. <dependency>
  52. <groupId>javax.servlet</groupId>
  53. <artifactId>javax.servlet-api</artifactId>
  54. <version>3.1.0</version>
  55. <scope>provided</scope>
  56. </dependency>
  57. <dependency>
  58. <groupId>com.fasterxml.jackson.core</groupId>
  59. <artifactId>jackson-databind</artifactId>
  60. <version>2.9.0</version>
  61. </dependency>
  62. </dependencies>
  63. <build>
  64. <plugins>
  65. <plugin>
  66. <groupId>org.apache.tomcat.maven</groupId>
  67. <artifactId>tomcat7-maven-plugin</artifactId>
  68. <version>2.1</version>
  69. <configuration>
  70. <port>80</port>
  71. <path>/</path>
  72. </configuration>
  73. </plugin>
  74. </plugins>
  75. </build>
  76. </project>

步骤3:创建项目包结构

😧 SpringMVC_day02 - 图2

  • config目录存放的是相关的配置类
  • controller编写的是Controller类
  • dao存放的是Dao接口,因为使用的是Mapper接口代理方式,所以没有实现类包
  • service存的是Service接口,impl存放的是Service实现类
  • resources:存入的是配置文件,如Jdbc.properties
  • webapp:目录可以存放静态资源
  • test/java:存放的是测试类

步骤4:创建SpringConfig配置类

  1. @Configuration
  2. @ComponentScan({"com.itheima.service"})
  3. @PropertySource("classpath:jdbc.properties")
  4. @Import({JdbcConfig.class,MyBatisConfig.class})
  5. @EnableTransactionManagement
  6. public class SpringConfig {
  7. }

步骤5:创建JdbcConfig配置类

  1. public class JdbcConfig {
  2. @Value("${jdbc.driver}")
  3. private String driver;
  4. @Value("${jdbc.url}")
  5. private String url;
  6. @Value("${jdbc.username}")
  7. private String username;
  8. @Value("${jdbc.password}")
  9. private String password;
  10. @Bean
  11. public DataSource dataSource(){
  12. DruidDataSource dataSource = new DruidDataSource();
  13. dataSource.setDriverClassName(driver);
  14. dataSource.setUrl(url);
  15. dataSource.setUsername(username);
  16. dataSource.setPassword(password);
  17. return dataSource;
  18. }
  19. @Bean
  20. public PlatformTransactionManager transactionManager(DataSource dataSource){
  21. DataSourceTransactionManager ds = new DataSourceTransactionManager();
  22. ds.setDataSource(dataSource);
  23. return ds;
  24. }
  25. }

步骤6:创建MybatisConfig配置类

  1. public class MyBatisConfig {
  2. @Bean
  3. public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
  4. SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
  5. factoryBean.setDataSource(dataSource);
  6. factoryBean.setTypeAliasesPackage("com.itheima.domain");
  7. return factoryBean;
  8. }
  9. @Bean
  10. public MapperScannerConfigurer mapperScannerConfigurer(){
  11. MapperScannerConfigurer msc = new MapperScannerConfigurer();
  12. msc.setBasePackage("com.itheima.dao");
  13. return msc;
  14. }
  15. }

步骤7:创建jdbc.properties

在resources下提供jdbc.properties,设置数据库连接四要素

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/ssm_db
  3. jdbc.username=root
  4. jdbc.password=root

步骤8:创建SpringMVC配置类

  1. @Configuration
  2. @ComponentScan("com.itheima.controller")
  3. @EnableWebMvc
  4. public class SpringMvcConfig {
  5. }

步骤9:创建Web项目入口配置类

  1. public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
  2. //加载Spring配置类
  3. protected Class<?>[] getRootConfigClasses() {
  4. return new Class[]{SpringConfig.class};
  5. }
  6. //加载SpringMVC配置类
  7. protected Class<?>[] getServletConfigClasses() {
  8. return new Class[]{SpringMvcConfig.class};
  9. }
  10. //设置SpringMVC请求地址拦截规则
  11. protected String[] getServletMappings() {
  12. return new String[]{"/"};
  13. }
  14. //设置post请求中文乱码过滤器
  15. @Override
  16. protected Filter[] getServletFilters() {
  17. CharacterEncodingFilter filter = new CharacterEncodingFilter();
  18. filter.setEncoding("utf-8");
  19. return new Filter[]{filter};
  20. }
  21. }

至此SSM整合的环境就已经搭建好了。在这个环境上,我们如何进行功能模块的开发呢?

1.3 功能模块开发

需求:对表tbl_book进行新增、修改、删除、根据ID查询和查询所有

步骤1:创建数据库及表

  1. create database ssm_db character set utf8;
  2. use ssm_db;
  3. create table tbl_book(
  4. id int primary key auto_increment,
  5. type varchar(20),
  6. name varchar(50),
  7. description varchar(255)
  8. )
  9. insert into `tbl_book`(`id`,`type`,`name`,`description`) values (1,'计算机理论','Spring实战 第五版','Spring入门经典教程,深入理解Spring原理技术内幕'),(2,'计算机理论','Spring 5核心原理与30个类手写实践','十年沉淀之作,手写Spring精华思想'),(3,'计算机理论','Spring 5设计模式','深入Spring源码刨析Spring源码中蕴含的10大设计模式'),(4,'计算机理论','Spring MVC+Mybatis开发从入门到项目实战','全方位解析面向Web应用的轻量级框架,带你成为Spring MVC开发高手'),(5,'计算机理论','轻量级Java Web企业应用实战','源码级刨析Spring框架,适合已掌握Java基础的读者'),(6,'计算机理论','Java核心技术 卷Ⅰ 基础知识(原书第11版)','Core Java第11版,Jolt大奖获奖作品,针对Java SE9、10、11全面更新'),(7,'计算机理论','深入理解Java虚拟机','5个纬度全面刨析JVM,大厂面试知识点全覆盖'),(8,'计算机理论','Java编程思想(第4版)','Java学习必读经典,殿堂级著作!赢得了全球程序员的广泛赞誉'),(9,'计算机理论','零基础学Java(全彩版)','零基础自学编程的入门图书,由浅入深,详解Java语言的编程思想和核心技术'),(10,'市场营销','直播就这么做:主播高效沟通实战指南','李子柒、李佳奇、薇娅成长为网红的秘密都在书中'),(11,'市场营销','直播销讲实战一本通','和秋叶一起学系列网络营销书籍'),(12,'市场营销','直播带货:淘宝、天猫直播从新手到高手','一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+');

步骤2:编写模型类

  1. public class Book {
  2. private Integer id;
  3. private String type;
  4. private String name;
  5. private String description;
  6. //getter...setter...toString省略
  7. }

步骤3:编写Dao接口

  1. public interface BookDao {
  2. // @Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
  3. @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
  4. public void save(Book book);
  5. @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
  6. public void update(Book book);
  7. @Delete("delete from tbl_book where id = #{id}")
  8. public void delete(Integer id);
  9. @Select("select * from tbl_book where id = #{id}")
  10. public Book getById(Integer id);
  11. @Select("select * from tbl_book")
  12. public List<Book> getAll();
  13. }

步骤4:编写Service接口和实现类

  1. @Transactional
  2. public interface BookService {
  3. /**
  4. * 保存
  5. * @param book
  6. * @return
  7. */
  8. public boolean save(Book book);
  9. /**
  10. * 修改
  11. * @param book
  12. * @return
  13. */
  14. public boolean update(Book book);
  15. /**
  16. * 按id删除
  17. * @param id
  18. * @return
  19. */
  20. public boolean delete(Integer id);
  21. /**
  22. * 按id查询
  23. * @param id
  24. * @return
  25. */
  26. public Book getById(Integer id);
  27. /**
  28. * 查询全部
  29. * @return
  30. */
  31. public List<Book> getAll();
  32. }
  1. @Service
  2. public class BookServiceImpl implements BookService {
  3. @Autowired
  4. private BookDao bookDao;
  5. public boolean save(Book book) {
  6. bookDao.save(book);
  7. return true;
  8. }
  9. public boolean update(Book book) {
  10. bookDao.update(book);
  11. return true;
  12. }
  13. public boolean delete(Integer id) {
  14. bookDao.delete(id);
  15. return true;
  16. }
  17. public Book getById(Integer id) {
  18. return bookDao.getById(id);
  19. }
  20. public List<Book> getAll() {
  21. return bookDao.getAll();
  22. }
  23. }

说明:

  • bookDao在Service中注入的会提示一个红线提示,为什么呢?

    • BookDao是一个接口,没有实现类,接口是不能创建对象的,所以最终注入的应该是代理对象
    • 代理对象是由Spring的IOC容器来创建管理的
    • IOC容器又是在Web服务器启动的时候才会创建
    • IDEA在检测依赖关系的时候,没有找到适合的类注入,所以会提示错误提示
    • 但是程序运行的时候,代理对象就会被创建,框架会使用DI进行注入,所以程序运行无影响。
  • 如何解决上述问题?

    • 可以不用理会,因为运行是正常的
    • 设置错误提示级别
      😧 SpringMVC_day02 - 图3

步骤5:编写Contorller类

  1. @RestController
  2. @RequestMapping("/books")
  3. public class BookController {
  4. @Autowired
  5. private BookService bookService;
  6. @PostMapping
  7. public boolean save(@RequestBody Book book) {
  8. return bookService.save(book);
  9. }
  10. @PutMapping
  11. public boolean update(@RequestBody Book book) {
  12. return bookService.update(book);
  13. }
  14. @DeleteMapping("/{id}")
  15. public boolean delete(@PathVariable Integer id) {
  16. return bookService.delete(id);
  17. }
  18. @GetMapping("/{id}")
  19. public Book getById(@PathVariable Integer id) {
  20. return bookService.getById(id);
  21. }
  22. @GetMapping
  23. public List<Book> getAll() {
  24. return bookService.getAll();
  25. }
  26. }

对于图书模块的增删改查就已经完成了编写,我们可以从后往前写也可以从前往后写,最终只需要能把功能实现即可。

接下来我们就先把业务层的代码使用Spring整合Junit的知识点进行单元测试:

1.4 单元测试

步骤1:新建测试类

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(classes = SpringConfig.class)
  3. public class BookServiceTest {
  4. }

步骤2:注入Service类

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(classes = SpringConfig.class)
  3. public class BookServiceTest {
  4. @Autowired
  5. private BookService bookService;
  6. }

步骤3:编写测试方法

我们先来对查询进行单元测试。

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(classes = SpringConfig.class)
  3. public class BookServiceTest {
  4. @Autowired
  5. private BookService bookService;
  6. @Test
  7. public void testGetById(){
  8. Book book = bookService.getById(1);
  9. System.out.println(book);
  10. }
  11. @Test
  12. public void testGetAll(){
  13. List<Book> all = bookService.getAll();
  14. System.out.println(all);
  15. }
  16. }

根据ID查询,测试的结果为:

😧 SpringMVC_day02 - 图4

查询所有,测试的结果为:

😧 SpringMVC_day02 - 图5

1.5 PostMan测试

新增

http://localhost/books

  1. {
  2. "type":"类别测试数据",
  3. "name":"书名测试数据",
  4. "description":"描述测试数据"
  5. }

😧 SpringMVC_day02 - 图6

修改

http://localhost/books

  1. {
  2. "id":13,
  3. "type":"类别测试数据",
  4. "name":"书名测试数据",
  5. "description":"描述测试数据"
  6. }

😧 SpringMVC_day02 - 图7

删除

http://localhost/books/14

😧 SpringMVC_day02 - 图8

查询单个

http://localhost/books/1

😧 SpringMVC_day02 - 图9

查询所有

http://localhost/books

😧 SpringMVC_day02 - 图10

2,统一结果封装

2.1 表现层与前端数据传输协议定义

SSM整合以及功能模块开发完成后,接下来,我们在上述案例的基础上分析下有哪些问题需要我们去解决下。首先第一个问题是:

  • 在Controller层增删改返回给前端的是boolean类型数据
    😧 SpringMVC_day02 - 图11
  • 在Controller层查询单个返回给前端的是对象
    😧 SpringMVC_day02 - 图12
  • 在Controller层查询所有返回给前端的是集合对象
    😧 SpringMVC_day02 - 图13

目前我们就已经有三种数据类型返回给前端,如果随着业务的增长,我们需要返回的数据类型会越来越多。对于前端开发人员在解析数据的时候就比较凌乱了,所以对于前端来说,如果后台能够返回一个统一的数据结果,前端在解析的时候就可以按照一种方式进行解析。开发就会变得更加简单。

所以我们就想能不能将返回结果的数据进行统一,具体如何来做,大体的思路为:

  • 为了封装返回的结果数据:创建结果模型类,封装数据到data属性中
  • 为了封装返回的数据是何种操作及是否操作成功:封装操作结果到code属性中
  • 操作失败后为了封装返回的错误信息:封装特殊消息到message(msg)属性中

😧 SpringMVC_day02 - 图14

根据分析,我们可以设置统一数据返回结果类

  1. public class Result{
  2. private Object data;
  3. private Integer code;
  4. private String msg;
  5. }

注意:Result类名及类中的字段并不是固定的,可以根据需要自行增减提供若干个构造方法,方便操作。

2.2 表现层与前端数据传输协议实现

前面我们已经分析了如何封装返回结果数据,具体在项目中该如何实现,我们通过个例子来操作一把

2.2.1 环境准备

  • 创建一个Web的Maven项目
  • pom.xml添加SSM整合所需jar包
  • 创建对应的配置类
  • 编写Controller、Service接口、Service实现类、Dao接口和模型类
  • resources下提供jdbc.properties配置文件

因为这个项目环境的内容和SSM整合的内容是一致的,所以我们就不在把代码粘出来了,大家在练习的时候可以在前面整合的例子案例环境下,进行本节内容的开发。

最终创建好的项目结构如下:

😧 SpringMVC_day02 - 图15

2.2.2 结果封装

对于结果封装,我们应该是在表现层进行处理,所以我们把结果类放在controller包下,当然你也可以放在domain包,这个都是可以的,具体如何实现结果封装,具体的步骤为:

步骤1:创建Result类
  1. public class Result {
  2. //描述统一格式中的数据
  3. private Object data;
  4. //描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败
  5. private Integer code;
  6. //描述统一格式中的消息,可选属性
  7. private String msg;
  8. public Result() {
  9. }
  10. //构造方法是方便对象的创建
  11. public Result(Integer code,Object data) {
  12. this.data = data;
  13. this.code = code;
  14. }
  15. //构造方法是方便对象的创建
  16. public Result(Integer code, Object data, String msg) {
  17. this.data = data;
  18. this.code = code;
  19. this.msg = msg;
  20. }
  21. //setter...getter...省略
  22. }

步骤2:定义返回码Code类
  1. //状态码
  2. public class Code {
  3. public static final Integer SAVE_OK = 20011;
  4. public static final Integer DELETE_OK = 20021;
  5. public static final Integer UPDATE_OK = 20031;
  6. public static final Integer GET_OK = 20041;
  7. public static final Integer SAVE_ERR = 20010;
  8. public static final Integer DELETE_ERR = 20020;
  9. public static final Integer UPDATE_ERR = 20030;
  10. public static final Integer GET_ERR = 20040;
  11. }

注意:code类中的常量设计也不是固定的,可以根据需要自行增减,例如将查询再进行细分为GET_OK,GET_ALL_OK,GET_PAGE_OK等。

步骤3:修改Controller类的返回值
  1. //统一每一个控制器方法返回值
  2. @RestController
  3. @RequestMapping("/books")
  4. public class BookController {
  5. @Autowired
  6. private BookService bookService;
  7. @PostMapping
  8. public Result save(@RequestBody Book book) {
  9. boolean flag = bookService.save(book);
  10. return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
  11. }
  12. @PutMapping
  13. public Result update(@RequestBody Book book) {
  14. boolean flag = bookService.update(book);
  15. return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
  16. }
  17. @DeleteMapping("/{id}")
  18. public Result delete(@PathVariable Integer id) {
  19. boolean flag = bookService.delete(id);
  20. return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
  21. }
  22. @GetMapping("/{id}")
  23. public Result getById(@PathVariable Integer id) {
  24. Book book = bookService.getById(id);
  25. Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
  26. String msg = book != null ? "" : "数据查询失败,请重试!";
  27. return new Result(code,book,msg);
  28. }
  29. @GetMapping
  30. public Result getAll() {
  31. List<Book> bookList = bookService.getAll();
  32. Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
  33. String msg = bookList != null ? "" : "数据查询失败,请重试!";
  34. return new Result(code,bookList,msg);
  35. }
  36. }

步骤4:启动服务测试

😧 SpringMVC_day02 - 图16

至此,我们的返回结果就已经能以一种统一的格式返回给前端。前端根据返回的结果,先从中获取code,根据code判断,如果成功则取data属性的值,如果失败,则取msg中的值做提示。

3,统一异常处理

3.1 问题描述

在讲解这一部分知识点之前,我们先来演示个效果,修改BookController类的getById方法

  1. @GetMapping("/{id}")
  2. public Result getById(@PathVariable Integer id) {
  3. //手动添加一个错误信息
  4. if(id==1){
  5. int i = 1/0;
  6. }
  7. Book book = bookService.getById(id);
  8. Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
  9. String msg = book != null ? "" : "数据查询失败,请重试!";
  10. return new Result(code,book,msg);
  11. }

重新启动运行项目,使用PostMan发送请求,当传入的id为1,则会出现如下效果:

😧 SpringMVC_day02 - 图17

前端接收到这个信息后和之前我们约定的格式不一致,这个问题该如何解决?

在解决问题之前,我们先来看下异常的种类及出现异常的原因:

  • 框架内部抛出的异常:因使用不合规导致
  • 数据层抛出的异常:因外部服务器故障导致(例如:服务器访问超时)
  • 业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写操作,导致索引异常等)
  • 表现层抛出的异常:因数据收集、校验等规则导致(例如:不匹配的数据类型间导致异常)
  • 工具类抛出的异常:因工具类书写不严谨不够健壮导致(例如:必要释放的连接长期未释放等)

看完上面这些出现异常的位置,你会发现,在我们开发的任何一个位置都有可能出现异常,而且这些异常是不能避免的。所以我们就得将异常进行处理。

思考

  1. 各个层级均出现异常,异常处理代码书写在哪一层?
    所有的异常均抛出到表现层进行处理
  2. 异常的种类很多,表现层如何将所有的异常都处理到呢?
    异常分类
  3. 表现层处理异常,每个方法中单独书写,代码书写量巨大且意义不强,如何解决?
    AOP

对于上面这些问题及解决方案,SpringMVC已经为我们提供了一套解决方案:

  • 异常处理器:

    • 集中的、统一的处理项目中出现的异常。
      😧 SpringMVC_day02 - 图18

3.2 异常处理器的使用

3.2.1 环境准备

  • 创建一个Web的Maven项目
  • pom.xml添加SSM整合所需jar包
  • 创建对应的配置类
  • 编写Controller、Service接口、Service实现类、Dao接口和模型类
  • resources下提供jdbc.properties配置文件

内容参考前面的项目或者直接使用前面的项目进行本节内容的学习。

最终创建好的项目结构如下:

😧 SpringMVC_day02 - 图19

3.2.2 使用步骤

步骤1:创建异常处理器类
  1. //@RestControllerAdvice用于标识当前类为REST风格对应的异常处理器
  2. @RestControllerAdvice
  3. public class ProjectExceptionAdvice {
  4. //除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
  5. @ExceptionHandler(Exception.class)
  6. public void doException(Exception ex){
  7. System.out.println("嘿嘿,异常你哪里跑!")
  8. }
  9. }

确保SpringMvcConfig能够扫描到异常处理器类

步骤2:让程序抛出异常

修改BookController的getById方法,添加int i = 1/0.

  1. @GetMapping("/{id}")
  2. public Result getById(@PathVariable Integer id) {
  3. int i = 1/0;
  4. Book book = bookService.getById(id);
  5. Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
  6. String msg = book != null ? "" : "数据查询失败,请重试!";
  7. return new Result(code,book,msg);
  8. }

步骤3:运行程序,测试

😧 SpringMVC_day02 - 图20

说明异常已经被拦截并执行了doException方法。

异常处理器类返回结果给前端
  1. //@RestControllerAdvice用于标识当前类为REST风格对应的异常处理器
  2. @RestControllerAdvice
  3. public class ProjectExceptionAdvice {
  4. //除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
  5. @ExceptionHandler(Exception.class)
  6. public Result doException(Exception ex){
  7. System.out.println("嘿嘿,异常你哪里跑!")
  8. return new Result(666,null,"嘿嘿,异常你哪里跑!");
  9. }
  10. }

启动运行程序,测试

😧 SpringMVC_day02 - 图21

至此,就算后台执行的过程中抛出异常,最终也能按照我们和前端约定好的格式返回给前端。

知识点1:@RestControllerAdvice

名称 @RestControllerAdvice
类型 类注解
位置 Rest风格开发的控制器增强类定义上方
作用 为Rest风格开发的控制器类做增强

说明:此注解自带@ResponseBody注解与@Component注解,具备对应的功能

😧 SpringMVC_day02 - 图22

知识点2:@ExceptionHandler

名称 @ExceptionHandler
类型 方法注解
位置 专用于异常处理的控制器方法上方
作用 设置指定异常的处理方案,功能等同于控制器方法,
出现异常后终止原始控制器执行,并转入当前方法执行

说明:此类方法可以根据处理的异常不同,制作多个方法分别处理对应的异常

3.3 项目异常处理方案

3.3.1 异常分类

异常处理器我们已经能够使用了,那么在咱们的项目中该如何来处理异常呢?

因为异常的种类有很多,如果每一个异常都对应一个@ExceptionHandler,那得写多少个方法来处理各自的异常,所以我们在处理异常之前,需要对异常进行一个分类:

  • 业务异常(BusinessException)

    • 规范的用户行为产生的异常

      • 用户在页面输入内容的时候未按照指定格式进行数据填写,如在年龄框输入的是字符串
        😧 SpringMVC_day02 - 图23
    • 不规范的用户行为操作产生的异常

      • 如用户故意传递错误数据
        😧 SpringMVC_day02 - 图24
  • 系统异常(SystemException)

    • 项目运行过程中可预计但无法避免的异常

      • 比如数据库或服务器宕机
  • 其他异常(Exception)

    • 编程人员未预期到的异常,如:用到的文件不存在
      😧 SpringMVC_day02 - 图25

将异常分类以后,针对不同类型的异常,要提供具体的解决方案:

3.3.2 异常解决方案

  • 业务异常(BusinessException)

    • 发送对应消息传递给用户,提醒规范操作

      • 大家常见的就是提示用户名已存在或密码格式不正确等
  • 系统异常(SystemException)

    • 发送固定消息传递给用户,安抚用户

      • 系统繁忙,请稍后再试
      • 系统正在维护升级,请稍后再试
      • 系统出问题,请联系系统管理员等
    • 发送特定消息给运维人员,提醒维护

      • 可以发送短信、邮箱或者是公司内部通信软件
    • 记录日志

      • 发消息和记录日志对用户来说是不可见的,属于后台程序
  • 其他异常(Exception)

    • 发送固定消息传递给用户,安抚用户
    • 发送特定消息给编程人员,提醒维护(纳入预期范围内)

      • 一般是程序没有考虑全,比如未做非空校验等
    • 记录日志

3.3.3 异常解决方案的具体实现

思路:

1.先通过自定义异常,完成BusinessException和SystemException的定义

2.将其他异常包装成自定义异常类型

3.在异常处理器类中对不同的异常进行处理

步骤1:自定义异常类
  1. //自定义异常处理器,用于封装异常信息,对异常进行分类
  2. public class SystemException extends RuntimeException{
  3. private Integer code;
  4. public Integer getCode() {
  5. return code;
  6. }
  7. public void setCode(Integer code) {
  8. this.code = code;
  9. }
  10. public SystemException(Integer code, String message) {
  11. super(message);
  12. this.code = code;
  13. }
  14. public SystemException(Integer code, String message, Throwable cause) {
  15. super(message, cause);
  16. this.code = code;
  17. }
  18. }
  19. //自定义异常处理器,用于封装异常信息,对异常进行分类
  20. public class BusinessException extends RuntimeException{
  21. private Integer code;
  22. public Integer getCode() {
  23. return code;
  24. }
  25. public void setCode(Integer code) {
  26. this.code = code;
  27. }
  28. public BusinessException(Integer code, String message) {
  29. super(message);
  30. this.code = code;
  31. }
  32. public BusinessException(Integer code, String message, Throwable cause) {
  33. super(message, cause);
  34. this.code = code;
  35. }
  36. }

说明:

  • 让自定义异常类继承RuntimeException的好处是,后期在抛出这两个异常的时候,就不用在try…catch…或throws了
  • 自定义异常类中添加code属性的原因是为了更好的区分异常是来自哪个业务的

步骤2:将其他异常包成自定义异常

假如在BookServiceImpl的getById方法抛异常了,该如何来包装呢?

  1. public Book getById(Integer id) {
  2. //模拟业务异常,包装成自定义异常
  3. if(id == 1){
  4. throw new BusinessException(Code.BUSINESS_ERR,"请不要使用你的技术挑战我的耐性!");
  5. }
  6. //模拟系统异常,将可能出现的异常进行包装,转换成自定义异常
  7. try{
  8. int i = 1/0;
  9. }catch (Exception e){
  10. throw new SystemException(Code.SYSTEM_TIMEOUT_ERR,"服务器访问超时,请重试!",e);
  11. }
  12. return bookDao.getById(id);
  13. }

具体的包装方式有:

  • 方式一:try{}catch(){}在catch中重新throw我们自定义异常即可。
  • 方式二:直接throw自定义异常即可

上面为了使code看着更专业些,我们在Code类中再新增需要的属性

  1. //状态码
  2. public class Code {
  3. public static final Integer SAVE_OK = 20011;
  4. public static final Integer DELETE_OK = 20021;
  5. public static final Integer UPDATE_OK = 20031;
  6. public static final Integer GET_OK = 20041;
  7. public static final Integer SAVE_ERR = 20010;
  8. public static final Integer DELETE_ERR = 20020;
  9. public static final Integer UPDATE_ERR = 20030;
  10. public static final Integer GET_ERR = 20040;
  11. public static final Integer SYSTEM_ERR = 50001;
  12. public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
  13. public static final Integer SYSTEM_UNKNOW_ERR = 59999;
  14. public static final Integer BUSINESS_ERR = 60002;
  15. }

步骤3:处理器类中处理自定义异常
  1. //@RestControllerAdvice用于标识当前类为REST风格对应的异常处理器
  2. @RestControllerAdvice
  3. public class ProjectExceptionAdvice {
  4. //@ExceptionHandler用于设置当前处理器类对应的异常类型
  5. @ExceptionHandler(SystemException.class)
  6. public Result doSystemException(SystemException ex){
  7. //记录日志
  8. //发送消息给运维
  9. //发送邮件给开发人员,ex对象发送给开发人员
  10. return new Result(ex.getCode(),null,ex.getMessage());
  11. }
  12. @ExceptionHandler(BusinessException.class)
  13. public Result doBusinessException(BusinessException ex){
  14. return new Result(ex.getCode(),null,ex.getMessage());
  15. }
  16. //除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
  17. @ExceptionHandler(Exception.class)
  18. public Result doOtherException(Exception ex){
  19. //记录日志
  20. //发送消息给运维
  21. //发送邮件给开发人员,ex对象发送给开发人员
  22. return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
  23. }
  24. }

步骤4:运行程序

根据ID查询,

如果传入的参数为1,会报BusinessException

😧 SpringMVC_day02 - 图26

如果传入的是其他参数,会报SystemException

😧 SpringMVC_day02 - 图27

对于异常我们就已经处理完成了,不管后台哪一层抛出异常,都会以我们与前端约定好的方式进行返回,前端只需要把信息获取到,根据返回的正确与否来展示不同的内容即可。

小结

以后项目中的异常处理方式为:

😧 SpringMVC_day02 - 图28

4,前后台协议联调

4.1 环境准备

  • 创建一个Web的Maven项目
  • pom.xml添加SSM整合所需jar包
  • 创建对应的配置类
  • 编写Controller、Service接口、Service实现类、Dao接口和模型类
  • resources下提供jdbc.properties配置文件

内容参考前面的项目或者直接使用前面的项目进行本节内容的学习。

最终创建好的项目结构如下:

😧 SpringMVC_day02 - 图29

  1. 资料\SSM功能页面下面的静态资源拷贝到webapp下。

😧 SpringMVC_day02 - 图30

  1. 因为添加了静态资源,SpringMVC会拦截,所有需要在SpringConfig的配置类中将静态资源进行放行。
  • 新建SpringMvcSupport
  1. @Configuration
  2. public class SpringMvcSupport extends WebMvcConfigurationSupport {
  3. @Override
  4. protected void addResourceHandlers(ResourceHandlerRegistry registry) {
  5. registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
  6. registry.addResourceHandler("/css/**").addResourceLocations("/css/");
  7. registry.addResourceHandler("/js/**").addResourceLocations("/js/");
  8. registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
  9. }
  10. }
  • 在SpringMvcConfig中扫描SpringMvcSupport
  1. @Configuration
  2. @ComponentScan({"com.itheima.controller","com.itheima.config"})
  3. @EnableWebMvc
  4. public class SpringMvcConfig {
  5. }

接下来我们就需要将所有的列表查询、新增、修改、删除等功能一个个来实现下。

4.2 列表功能

😧 SpringMVC_day02 - 图31

需求:页面加载完后发送异步请求到后台获取列表数据进行展示。

1.找到页面的钩子函数,created()

2.created()方法中调用了this.getAll()方法

3.在getAll()方法中使用axios发送异步请求从后台获取数据

4.访问的路径为http://localhost/books

5.返回数据

返回数据res.data的内容如下:

  1. {
  2. "data": [
  3. {
  4. "id": 1,
  5. "type": "计算机理论",
  6. "name": "Spring实战 第五版",
  7. "description": "Spring入门经典教程,深入理解Spring原理技术内幕"
  8. },
  9. {
  10. "id": 2,
  11. "type": "计算机理论",
  12. "name": "Spring 5核心原理与30个类手写实践",
  13. "description": "十年沉淀之作,手写Spring精华思想"
  14. },...
  15. ],
  16. "code": 20041,
  17. "msg": ""
  18. }

发送方式:

  1. getAll() {
  2. //发送ajax请求
  3. axios.get("/books").then((res)=>{
  4. this.dataList = res.data.data;
  5. });
  6. }

😧 SpringMVC_day02 - 图32

4.3 添加功能

😧 SpringMVC_day02 - 图33

需求:完成图片的新增功能模块

1.找到页面上的新建按钮,按钮上绑定了@click="handleCreate()"方法

2.在method中找到handleCreate方法,方法中打开新增面板

3.新增面板中找到确定按钮,按钮上绑定了@click="handleAdd()"方法

4.在method中找到handleAdd方法

5.在方法中发送请求和数据,响应成功后将新增面板关闭并重新查询数据

handleCreate打开新增面板

  1. handleCreate() {
  2. this.dialogFormVisible = true;
  3. },

handleAdd方法发送异步请求并携带数据

  1. handleAdd () {
  2. //发送ajax请求
  3. //this.formData是表单中的数据,最后是一个json数据
  4. axios.post("/books",this.formData).then((res)=>{
  5. this.dialogFormVisible = false;
  6. this.getAll();
  7. });
  8. }

4.4 添加功能状态处理

基础的新增功能已经完成,但是还有一些问题需要解决下:

需求:新增成功是关闭面板,重新查询数据,那么新增失败以后该如何处理?

1.在handlerAdd方法中根据后台返回的数据来进行不同的处理

2.如果后台返回的是成功,则提示成功信息,并关闭面板

3.如果后台返回的是失败,则提示错误信息

(1)修改前端页面

  1. handleAdd () {
  2. //发送ajax请求
  3. axios.post("/books",this.formData).then((res)=>{
  4. //如果操作成功,关闭弹层,显示数据
  5. if(res.data.code == 20011){
  6. this.dialogFormVisible = false;
  7. this.$message.success("添加成功");
  8. }else if(res.data.code == 20010){
  9. this.$message.error("添加失败");
  10. }else{
  11. this.$message.error(res.data.msg);
  12. }
  13. }).finally(()=>{
  14. this.getAll();
  15. });
  16. }

(2)后台返回操作结果,将Dao层的增删改方法返回值从void改成int

  1. public interface BookDao {
  2. // @Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
  3. @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
  4. public int save(Book book);
  5. @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
  6. public int update(Book book);
  7. @Delete("delete from tbl_book where id = #{id}")
  8. public int delete(Integer id);
  9. @Select("select * from tbl_book where id = #{id}")
  10. public Book getById(Integer id);
  11. @Select("select * from tbl_book")
  12. public List<Book> getAll();
  13. }

(3)在BookServiceImpl中,增删改方法根据DAO的返回值来决定返回true/false

  1. @Service
  2. public class BookServiceImpl implements BookService {
  3. @Autowired
  4. private BookDao bookDao;
  5. public boolean save(Book book) {
  6. return bookDao.save(book) > 0;
  7. }
  8. public boolean update(Book book) {
  9. return bookDao.update(book) > 0;
  10. }
  11. public boolean delete(Integer id) {
  12. return bookDao.delete(id) > 0;
  13. }
  14. public Book getById(Integer id) {
  15. if(id == 1){
  16. throw new BusinessException(Code.BUSINESS_ERR,"请不要使用你的技术挑战我的耐性!");
  17. }
  18. // //将可能出现的异常进行包装,转换成自定义异常
  19. // try{
  20. // int i = 1/0;
  21. // }catch (Exception e){
  22. // throw new SystemException(Code.SYSTEM_TIMEOUT_ERR,"服务器访问超时,请重试!",e);
  23. // }
  24. return bookDao.getById(id);
  25. }
  26. public List<Book> getAll() {
  27. return bookDao.getAll();
  28. }
  29. }

(4)测试错误情况,将图书类别长度设置超出范围即可

😧 SpringMVC_day02 - 图34

处理完新增后,会发现新增还存在一个问题,

新增成功后,再次点击新增按钮会发现之前的数据还存在,这个时候就需要在新增的时候将表单内容清空。

  1. resetForm(){
  2. this.formData = {};
  3. }
  4. handleCreate() {
  5. this.dialogFormVisible = true;
  6. this.resetForm();
  7. }

4.5 修改功能

😧 SpringMVC_day02 - 图35

需求:完成图书信息的修改功能

1.找到页面中的编辑按钮,该按钮绑定了@click="handleUpdate(scope.row)"

2.在method的handleUpdate方法中发送异步请求根据ID查询图书信息

3.根据后台返回的结果,判断是否查询成功

如果查询成功打开修改面板回显数据,如果失败提示错误信息

4.修改完成后找到修改面板的确定按钮,该按钮绑定了@click="handleEdit()"

5.在method的handleEdit方法中发送异步请求提交修改数据

6.根据后台返回的结果,判断是否修改成功

如果成功提示错误信息,关闭修改面板,重新查询数据,如果失败提示错误信息

scope.row代表的是当前行的行数据,也就是说,scope.row就是选中行对应的json数据,如下:

  1. {
  2. "id": 1,
  3. "type": "计算机理论",
  4. "name": "Spring实战 第五版",
  5. "description": "Spring入门经典教程,深入理解Spring原理技术内幕"
  6. }

修改handleUpdate方法

  1. //弹出编辑窗口
  2. handleUpdate(row) {
  3. // console.log(row); //row.id 查询条件
  4. //查询数据,根据id查询
  5. axios.get("/books/"+row.id).then((res)=>{
  6. if(res.data.code == 20041){
  7. //展示弹层,加载数据
  8. this.formData = res.data.data;
  9. this.dialogFormVisible4Edit = true;
  10. }else{
  11. this.$message.error(res.data.msg);
  12. }
  13. });
  14. }

修改handleEdit方法

  1. handleEdit() {
  2. //发送ajax请求
  3. axios.put("/books",this.formData).then((res)=>{
  4. //如果操作成功,关闭弹层,显示数据
  5. if(res.data.code == 20031){
  6. this.dialogFormVisible4Edit = false;
  7. this.$message.success("修改成功");
  8. }else if(res.data.code == 20030){
  9. this.$message.error("修改失败");
  10. }else{
  11. this.$message.error(res.data.msg);
  12. }
  13. }).finally(()=>{
  14. this.getAll();
  15. });
  16. }

至此修改功能就已经完成。

4.6 删除功能

😧 SpringMVC_day02 - 图36

需求:完成页面的删除功能。

1.找到页面的删除按钮,按钮上绑定了@click="handleDelete(scope.row)"

2.method的handleDelete方法弹出提示框

3.用户点击取消,提示操作已经被取消。

4.用户点击确定,发送异步请求并携带需要删除数据的主键ID

5.根据后台返回结果做不同的操作

如果返回成功,提示成功信息,并重新查询数据

如果返回失败,提示错误信息,并重新查询数据

修改handleDelete方法

  1. handleDelete(row) {
  2. //1.弹出提示框
  3. this.$confirm("此操作永久删除当前数据,是否继续?","提示",{
  4. type:'info'
  5. }).then(()=>{
  6. //2.做删除业务
  7. axios.delete("/books/"+row.id).then((res)=>{
  8. if(res.data.code == 20021){
  9. this.$message.success("删除成功");
  10. }else{
  11. this.$message.error("删除失败");
  12. }
  13. }).finally(()=>{
  14. this.getAll();
  15. });
  16. }).catch(()=>{
  17. //3.取消删除
  18. this.$message.info("取消删除操作");
  19. });
  20. }

接下来,下面是一个完整页面

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <!-- 页面meta -->
  5. <meta charset="utf-8">
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. <title>SpringMVC案例</title>
  8. <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
  9. <!-- 引入样式 -->
  10. <link rel="stylesheet" href="../plugins/elementui/index.css">
  11. <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
  12. <link rel="stylesheet" href="../css/style.css">
  13. </head>
  14. <body class="hold-transition">
  15. <div id="app">
  16. <div class="content-header">
  17. <h1>图书管理</h1>
  18. </div>
  19. <div class="app-container">
  20. <div class="box">
  21. <div class="filter-container">
  22. <el-input placeholder="图书名称" v-model="pagination.queryString" style="width: 200px;" class="filter-item"></el-input>
  23. <el-button @click="getAll()" class="dalfBut">查询</el-button>
  24. <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
  25. </div>
  26. <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
  27. <el-table-column type="index" align="center" label="序号"></el-table-column>
  28. <el-table-column prop="type" label="图书类别" align="center"></el-table-column>
  29. <el-table-column prop="name" label="图书名称" align="center"></el-table-column>
  30. <el-table-column prop="description" label="描述" align="center"></el-table-column>
  31. <el-table-column label="操作" align="center">
  32. <template slot-scope="scope">
  33. <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
  34. <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
  35. </template>
  36. </el-table-column>
  37. </el-table>
  38. <!-- 新增标签弹层 -->
  39. <div class="add-form">
  40. <el-dialog title="新增图书" :visible.sync="dialogFormVisible">
  41. <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
  42. <el-row>
  43. <el-col :span="12">
  44. <el-form-item label="图书类别" prop="type">
  45. <el-input v-model="formData.type"/>
  46. </el-form-item>
  47. </el-col>
  48. <el-col :span="12">
  49. <el-form-item label="图书名称" prop="name">
  50. <el-input v-model="formData.name"/>
  51. </el-form-item>
  52. </el-col>
  53. </el-row>
  54. <el-row>
  55. <el-col :span="24">
  56. <el-form-item label="描述">
  57. <el-input v-model="formData.description" type="textarea"></el-input>
  58. </el-form-item>
  59. </el-col>
  60. </el-row>
  61. </el-form>
  62. <div slot="footer" class="dialog-footer">
  63. <el-button @click="dialogFormVisible = false">取消</el-button>
  64. <el-button type="primary" @click="handleAdd()">确定</el-button>
  65. </div>
  66. </el-dialog>
  67. </div>
  68. <!-- 编辑标签弹层 -->
  69. <div class="add-form">
  70. <el-dialog title="编辑检查项" :visible.sync="dialogFormVisible4Edit">
  71. <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
  72. <el-row>
  73. <el-col :span="12">
  74. <el-form-item label="图书类别" prop="type">
  75. <el-input v-model="formData.type"/>
  76. </el-form-item>
  77. </el-col>
  78. <el-col :span="12">
  79. <el-form-item label="图书名称" prop="name">
  80. <el-input v-model="formData.name"/>
  81. </el-form-item>
  82. </el-col>
  83. </el-row>
  84. <el-row>
  85. <el-col :span="24">
  86. <el-form-item label="描述">
  87. <el-input v-model="formData.description" type="textarea"></el-input>
  88. </el-form-item>
  89. </el-col>
  90. </el-row>
  91. </el-form>
  92. <div slot="footer" class="dialog-footer">
  93. <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
  94. <el-button type="primary" @click="handleEdit()">确定</el-button>
  95. </div>
  96. </el-dialog>
  97. </div>
  98. </div>
  99. </div>
  100. </div>
  101. </body>
  102. <!-- 引入组件库 -->
  103. <script src="../js/vue.js"></script>
  104. <script src="../plugins/elementui/index.js"></script>
  105. <script type="text/javascript" src="../js/jquery.min.js"></script>
  106. <script src="../js/axios-0.18.0.js"></script>
  107. <script>
  108. var vue = new Vue({
  109. el: '#app',
  110. data:{
  111. pagination: {},
  112. dataList: [],//当前页要展示的列表数据
  113. formData: {},//表单数据
  114. dialogFormVisible: false,//控制表单是否可见
  115. dialogFormVisible4Edit:false,//编辑表单是否可见
  116. rules: {//校验规则
  117. type: [{ required: true, message: '图书类别为必填项', trigger: 'blur' }],
  118. name: [{ required: true, message: '图书名称为必填项', trigger: 'blur' }]
  119. }
  120. },
  121. //钩子函数,VUE对象初始化完成后自动执行
  122. created() {
  123. this.getAll();
  124. },
  125. methods: {
  126. //列表
  127. getAll() {
  128. //发送ajax请求
  129. axios.get("/books").then((res)=>{
  130. this.dataList = res.data.data;
  131. });
  132. },
  133. //弹出添加窗口
  134. handleCreate() {
  135. this.dialogFormVisible = true;
  136. this.resetForm();
  137. },
  138. //重置表单
  139. resetForm() {
  140. this.formData = {};
  141. },
  142. //添加
  143. handleAdd () {
  144. //发送ajax请求
  145. axios.post("/books",this.formData).then((res)=>{
  146. console.log(res.data);
  147. //如果操作成功,关闭弹层,显示数据
  148. if(res.data.code == 20011){
  149. this.dialogFormVisible = false;
  150. this.$message.success("添加成功");
  151. }else if(res.data.code == 20010){
  152. this.$message.error("添加失败");
  153. }else{
  154. this.$message.error(res.data.msg);
  155. }
  156. }).finally(()=>{
  157. this.getAll();
  158. });
  159. },
  160. //弹出编辑窗口
  161. handleUpdate(row) {
  162. // console.log(row); //row.id 查询条件
  163. //查询数据,根据id查询
  164. axios.get("/books/"+row.id).then((res)=>{
  165. // console.log(res.data.data);
  166. if(res.data.code == 20041){
  167. //展示弹层,加载数据
  168. this.formData = res.data.data;
  169. this.dialogFormVisible4Edit = true;
  170. }else{
  171. this.$message.error(res.data.msg);
  172. }
  173. });
  174. },
  175. //编辑
  176. handleEdit() {
  177. //发送ajax请求
  178. axios.put("/books",this.formData).then((res)=>{
  179. //如果操作成功,关闭弹层,显示数据
  180. if(res.data.code == 20031){
  181. this.dialogFormVisible4Edit = false;
  182. this.$message.success("修改成功");
  183. }else if(res.data.code == 20030){
  184. this.$message.error("修改失败");
  185. }else{
  186. this.$message.error(res.data.msg);
  187. }
  188. }).finally(()=>{
  189. this.getAll();
  190. });
  191. },
  192. // 删除
  193. handleDelete(row) {
  194. //1.弹出提示框
  195. this.$confirm("此操作永久删除当前数据,是否继续?","提示",{
  196. type:'info'
  197. }).then(()=>{
  198. //2.做删除业务
  199. axios.delete("/books/"+row.id).then((res)=>{
  200. if(res.data.code == 20021){
  201. this.$message.success("删除成功");
  202. }else{
  203. this.$message.error("删除失败");
  204. }
  205. }).finally(()=>{
  206. this.getAll();
  207. });
  208. }).catch(()=>{
  209. //3.取消删除
  210. this.$message.info("取消删除操作");
  211. });
  212. }
  213. }
  214. })
  215. </script>
  216. </html>

5,拦截器

对于拦截器这节的知识,我们需要学习如下内容:

  • 拦截器概念
  • 入门案例
  • 拦截器参数
  • 拦截器工作流程分析

5.1 拦截器概念

讲解拦截器的概念之前,我们先看一张图:

😧 SpringMVC_day02 - 图37

(1)浏览器发送一个请求会先到Tomcat的web服务器

(2)Tomcat服务器接收到请求以后,会去判断请求的是静态资源还是动态资源

(3)如果是静态资源,会直接到Tomcat的项目部署目录下去直接访问

(4)如果是动态资源,就需要交给项目的后台代码进行处理

(5)在找到具体的方法之前,我们可以去配置过滤器(可以配置多个),按照顺序进行执行

(6)然后进入到到中央处理器(SpringMVC中的内容),SpringMVC会根据配置的规则进行拦截

(7)如果满足规则,则进行处理,找到其对应的controller类中的方法进行执行,完成后返回结果

(8)如果不满足规则,则不进行处理

(9)这个时候,如果我们需要在每个Controller方法执行的前后添加业务,具体该如何来实现?

这个就是拦截器要做的事。

  • 拦截器(Interceptor)是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行
  • 作用:

    • 在指定的方法调用前后执行预先设定的代码
    • 阻止原始方法的执行
    • 总结:拦截器就是用来做增强

看完以后,大家会发现

  • 拦截器和过滤器在作用和执行顺序上也很相似

所以这个时候,就有一个问题需要思考:拦截器和过滤器之间的区别是什么?

  • 归属不同:Filter属于Servlet技术,Interceptor属于SpringMVC技术
  • 拦截内容不同:Filter对所有访问进行增强,Interceptor仅针对SpringMVC的访问进行增强

😧 SpringMVC_day02 - 图38

5.2 拦截器入门案例

5.2.1 环境准备

  • 创建一个Web的Maven项目
  • pom.xml添加SSM整合所需jar包
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.itheima</groupId>
  6. <artifactId>springmvc_12_interceptor</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. <packaging>war</packaging>
  9. <dependencies>
  10. <dependency>
  11. <groupId>javax.servlet</groupId>
  12. <artifactId>javax.servlet-api</artifactId>
  13. <version>3.1.0</version>
  14. <scope>provided</scope>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework</groupId>
  18. <artifactId>spring-webmvc</artifactId>
  19. <version>5.2.10.RELEASE</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>com.fasterxml.jackson.core</groupId>
  23. <artifactId>jackson-databind</artifactId>
  24. <version>2.9.0</version>
  25. </dependency>
  26. </dependencies>
  27. <build>
  28. <plugins>
  29. <plugin>
  30. <groupId>org.apache.tomcat.maven</groupId>
  31. <artifactId>tomcat7-maven-plugin</artifactId>
  32. <version>2.1</version>
  33. <configuration>
  34. <port>80</port>
  35. <path>/</path>
  36. </configuration>
  37. </plugin>
  38. <plugin>
  39. <groupId>org.apache.maven.plugins</groupId>
  40. <artifactId>maven-compiler-plugin</artifactId>
  41. <configuration>
  42. <source>8</source>
  43. <target>8</target>
  44. </configuration>
  45. </plugin>
  46. </plugins>
  47. </build>
  48. </project>
  • 创建对应的配置类
  1. public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
  2. protected Class<?>[] getRootConfigClasses() {
  3. return new Class[0];
  4. }
  5. protected Class<?>[] getServletConfigClasses() {
  6. return new Class[]{SpringMvcConfig.class};
  7. }
  8. protected String[] getServletMappings() {
  9. return new String[]{"/"};
  10. }
  11. //乱码处理
  12. @Override
  13. protected Filter[] getServletFilters() {
  14. CharacterEncodingFilter filter = new CharacterEncodingFilter();
  15. filter.setEncoding("UTF-8");
  16. return new Filter[]{filter};
  17. }
  18. }
  19. @Configuration
  20. @ComponentScan({"com.itheima.controller"})
  21. @EnableWebMvc
  22. public class SpringMvcConfig{
  23. }
  • 创建模型类Book
  1. public class Book {
  2. private String name;
  3. private double price;
  4. public String getName() {
  5. return name;
  6. }
  7. public void setName(String name) {
  8. this.name = name;
  9. }
  10. public double getPrice() {
  11. return price;
  12. }
  13. public void setPrice(double price) {
  14. this.price = price;
  15. }
  16. @Override
  17. public String toString() {
  18. return "Book{" +
  19. "书名='" + name + '\'' +
  20. ", 价格=" + price +
  21. '}';
  22. }
  23. }
  • 编写Controller
  1. @RestController
  2. @RequestMapping("/books")
  3. public class BookController {
  4. @PostMapping
  5. public String save(@RequestBody Book book){
  6. System.out.println("book save..." + book);
  7. return "{'module':'book save'}";
  8. }
  9. @DeleteMapping("/{id}")
  10. public String delete(@PathVariable Integer id){
  11. System.out.println("book delete..." + id);
  12. return "{'module':'book delete'}";
  13. }
  14. @PutMapping
  15. public String update(@RequestBody Book book){
  16. System.out.println("book update..."+book);
  17. return "{'module':'book update'}";
  18. }
  19. @GetMapping("/{id}")
  20. public String getById(@PathVariable Integer id){
  21. System.out.println("book getById..."+id);
  22. return "{'module':'book getById'}";
  23. }
  24. @GetMapping
  25. public String getAll(){
  26. System.out.println("book getAll...");
  27. return "{'module':'book getAll'}";
  28. }
  29. }

最终创建好的项目结构如下:

😧 SpringMVC_day02 - 图39

5.2.2 拦截器开发

步骤1:创建拦截器类

让类实现HandlerInterceptor接口,重写接口中的三个方法。

  1. @Component
  2. //定义拦截器类,实现HandlerInterceptor接口
  3. //注意当前类必须受Spring容器控制
  4. public class ProjectInterceptor implements HandlerInterceptor {
  5. @Override
  6. //原始方法调用前执行的内容
  7. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  8. System.out.println("preHandle...");
  9. return true;
  10. }
  11. @Override
  12. //原始方法调用后执行的内容
  13. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  14. System.out.println("postHandle...");
  15. }
  16. @Override
  17. //原始方法调用完成后执行的内容
  18. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  19. System.out.println("afterCompletion...");
  20. }
  21. }

注意:拦截器类要被SpringMVC容器扫描到。

步骤2:配置拦截器类
  1. @Configuration
  2. public class SpringMvcSupport extends WebMvcConfigurationSupport {
  3. @Autowired
  4. private ProjectInterceptor projectInterceptor;
  5. @Override
  6. protected void addResourceHandlers(ResourceHandlerRegistry registry) {
  7. registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
  8. }
  9. @Override
  10. protected void addInterceptors(InterceptorRegistry registry) {
  11. //配置拦截器
  12. registry.addInterceptor(projectInterceptor).addPathPatterns("/books" );
  13. }
  14. }

步骤3:SpringMVC添加SpringMvcSupport包扫描
  1. @Configuration
  2. @ComponentScan({"com.itheima.controller","com.itheima.config"})
  3. @EnableWebMvc
  4. public class SpringMvcConfig{
  5. }

步骤4:运行程序测试

使用PostMan发送http://localhost/books

😧 SpringMVC_day02 - 图40

如果发送http://localhost/books/100会发现拦截器没有被执行,原因是拦截器的addPathPatterns方法配置的拦截路径是/books,我们现在发送的是/books/100,所以没有匹配上,因此没有拦截,拦截器就不会执行。

步骤5:修改拦截器拦截规则
  1. @Configuration
  2. public class SpringMvcSupport extends WebMvcConfigurationSupport {
  3. @Autowired
  4. private ProjectInterceptor projectInterceptor;
  5. @Override
  6. protected void addResourceHandlers(ResourceHandlerRegistry registry) {
  7. registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
  8. }
  9. @Override
  10. protected void addInterceptors(InterceptorRegistry registry) {
  11. //配置拦截器
  12. registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*" );
  13. }
  14. }

这个时候,如果再次访问http://localhost/books/100,拦截器就会被执行。

最后说一件事,就是拦截器中的preHandler方法,如果返回true,则代表放行,会执行原始Controller类中要请求的方法,如果返回false,则代表拦截,后面的就不会再执行了。

步骤6:简化SpringMvcSupport的编写
  1. @Configuration
  2. @ComponentScan({"com.itheima.controller"})
  3. @EnableWebMvc
  4. //实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性
  5. public class SpringMvcConfig implements WebMvcConfigurer {
  6. @Autowired
  7. private ProjectInterceptor projectInterceptor;
  8. @Override
  9. public void addInterceptors(InterceptorRegistry registry) {
  10. //配置多拦截器
  11. registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
  12. }
  13. }

此后咱们就不用再写SpringMvcSupport类了。

最后我们来看下拦截器的执行流程:

😧 SpringMVC_day02 - 图41

当有拦截器后,请求会先进入preHandle方法,

  1. 如果方法返回true,则放行继续执行后面的handle[controller的方法]和后面的方法
  2. 如果返回false,则直接跳过后面方法的执行。

5.3 拦截器参数

5.3.1 前置处理方法

原始方法之前运行preHandle

  1. public boolean preHandle(HttpServletRequest request,
  2. HttpServletResponse response,
  3. Object handler) throws Exception {
  4. System.out.println("preHandle");
  5. return true;
  6. }
  • request:请求对象
  • response:响应对象
  • handler:被调用的处理器对象,本质上是一个方法对象,对反射中的Method对象进行了再包装

使用request对象可以获取请求数据中的内容,如获取请求头的Content-Type

  1. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  2. String contentType = request.getHeader("Content-Type");
  3. System.out.println("preHandle..."+contentType);
  4. return true;
  5. }

使用handler参数,可以获取方法的相关信息

  1. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  2. HandlerMethod hm = (HandlerMethod)handler;
  3. String methodName = hm.getMethod().getName();//可以获取方法的名称
  4. System.out.println("preHandle..."+methodName);
  5. return true;
  6. }

5.3.2 后置处理方法

原始方法运行后运行,如果原始方法被拦截,则不执行

  1. public void postHandle(HttpServletRequest request,
  2. HttpServletResponse response,
  3. Object handler,
  4. ModelAndView modelAndView) throws Exception {
  5. System.out.println("postHandle");
  6. }

前三个参数和上面的是一致的。

modelAndView:如果处理器执行完成具有返回结果,可以读取到对应数据与页面信息,并进行调整

因为咱们现在都是返回json数据,所以该参数的使用率不高。

5.3.3 完成处理方法

拦截器最后执行的方法,无论原始方法是否执行

  1. public void afterCompletion(HttpServletRequest request,
  2. HttpServletResponse response,
  3. Object handler,
  4. Exception ex) throws Exception {
  5. System.out.println("afterCompletion");
  6. }

前三个参数与上面的是一致的。

ex:如果处理器执行过程中出现异常对象,可以针对异常情况进行单独处理

因为我们现在已经有全局异常处理器类,所以该参数的使用率也不高。

这三个方法中,最常用的是preHandle,在这个方法中可以通过返回值来决定是否要进行放行,我们可以把业务逻辑放在该方法中,如果满足业务则返回true放行,不满足则返回false拦截。

5.4 拦截器链配置

目前,我们在项目中只添加了一个拦截器,如果有多个,该如何配置?配置多个后,执行顺序是什么?

5.4.1 配置多个拦截器

步骤1:创建拦截器类

实现接口,并重写接口中的方法

  1. @Component
  2. public class ProjectInterceptor2 implements HandlerInterceptor {
  3. @Override
  4. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  5. System.out.println("preHandle...222");
  6. return false;
  7. }
  8. @Override
  9. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  10. System.out.println("postHandle...222");
  11. }
  12. @Override
  13. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  14. System.out.println("afterCompletion...222");
  15. }
  16. }

步骤2:配置拦截器类
  1. @Configuration
  2. @ComponentScan({"com.itheima.controller"})
  3. @EnableWebMvc
  4. //实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性
  5. public class SpringMvcConfig implements WebMvcConfigurer {
  6. @Autowired
  7. private ProjectInterceptor projectInterceptor;
  8. @Autowired
  9. private ProjectInterceptor2 projectInterceptor2;
  10. @Override
  11. public void addInterceptors(InterceptorRegistry registry) {
  12. //配置多拦截器
  13. registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
  14. registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");
  15. }
  16. }

步骤3:运行程序,观察顺序

😧 SpringMVC_day02 - 图42

拦截器执行的顺序是和配置顺序有关。就和前面所提到的运维人员进入机房的案例,先进后出。

  • 当配置多个拦截器时,形成拦截器链
  • 拦截器链的运行顺序参照拦截器添加顺序为准
  • 当拦截器中出现对原始处理器的拦截,后面的拦截器均终止运行
  • 当拦截器运行中断,仅运行配置在前面的拦截器的afterCompletion操作

😧 SpringMVC_day02 - 图43

preHandle:与配置顺序相同,必定运行

postHandle:与配置顺序相反,可能不运行

afterCompletion:与配置顺序相反,可能不运行。

这个顺序不太好记,最终只需要把握住一个原则即可:以最终的运行结果为准