1. 导包
spring-webmvc(本身包含spring-context)、spring-jdbc、spring-test、junit、mybatis、mysql-connector-java、javax-servlet-api、jackson-databind
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<path>/</path>
<port>80</port>
</configuration>
</plugin>
</plugins>
</build>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
2. 添加SpringConfig、jdbc.properties、jdbcConfig、MybatisConfig、servletConfig
jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db1?useSSL=false
jdbc.username=root
jdbc.password=1234
jdbcConfig
public class JdbcConfig {
@Value("${jdbc.driver}")
String driver;
@Value("${jdbc.url}")
String url;
@Value("${jdbc.password}")
String password;
@Value("${jdbc.username}")
String username;
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setPassword(password);
dataSource.setUsername(username);
return dataSource;
}
//用于数据库事务
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
}
MybatisConfig
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setTypeAliasesPackage("com.xlm.domain");
return factoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc =new MapperScannerConfigurer();
msc.setBasePackage("com.xlm.dao");
return msc;
}
}
ServletConfig
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
SpringmvConfig
@Configuration
@ComponentScan("com.xlm.controller")
@EnableWebMvc //功能之一是完成json数据转换等
public class SpringMvcConfig {
}
SpringConfig
@Configuration
@ComponentScan("com.xlm.service")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
public class SpringConfig {
}
3. domain、dao、service、controller编写
book类的编写
public class Book {
private Integer id;
private String type;
private String name;
private String description;
@Override
public String toString() {
return "Book{" +
"id=" + id +
", type='" + type + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
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;
}
}
dao层接口的编写
public interface BookDao {
//@Insert("insert into tb_book values(null,#{type},#{name},#{description})")
@Insert("insert into tb_book (type,name,description) values(#{type},#{name},#{description})") //前者是表里的字段,后者是Book类的属性
public void save(Book book);
@Update("update tb_book set type=#{type}, name=#{name}, description=#{description} where id = #{id}")
public void update(Book book);
@Delete("delete from tb_book where id = #{id}")
public void delete(Integer id);
@Select("select * from tb_book where id = #{id}")
public Book getById(Integer id);
@Select("select * from tb_book")
public List<Book> getAll();
}
service层接口
@Transactional //用于事务处理
public interface BookService {
/**
* 保存
* @param book
* @return
*/
public boolean save(Book book);
/**
* 修改
* @param book
* @return
*/
public boolean update(Book book);
/**
* 删除
* @param id
* @return
*/
public boolean delete(Integer id);
/**
* 查找
* @param id
* @return
*/
public Book getById(Integer id);
/**
* 查询全部
* @return
*/
public List<Book> getAll();
}
service层接口实现类
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
public boolean save(Book book) {
bookDao.save(book);
return true;
}
public boolean update(Book book) {
bookDao.update(book);
return true;
}
public boolean delete(Integer id) {
bookDao.delete(id);
return true;
}
public Book getById(Integer id) {
return bookDao.getById(id);
}
public List<Book> getAll() {
return bookDao.getAll();
}
}
controller实现类
-
先创建Result类和Code类
Code类
public class Code {
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20011;
public static final Integer UPDATE_OK = 20011;
public static final Integer GET_OK = 20011;
public static final Integer SAVE_ERR = 20010;
public static final Integer DELETE_ERR = 20010;
public static final Integer UPDATE_ERR = 20010;
public static final Integer GET_ERR = 20010;
}
Result类
public class Result {
private Object data;
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;
}
}
-
创建BookController类
@RestController
@RequestMapping("/books")
public class BookContoller {
@Autowired
private BookService bookService;
@PostMapping
public Result save(@RequestBody Book book) {
boolean flag = bookService.save(book);
return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
}
@PutMapping
public Result update(@RequestBody Book book) {
boolean flag = bookService.update(book);
return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
boolean flag = bookService.delete(id);
return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
}
@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);
}
@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);
}
}
4. 测试类测试服务层以及postman测试表示层
4.1服务层(service)测试
在java的test包下创建com.xxx.service包,在包中新建BookServiceTest类来对service服务层进行测试
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;
@RunWith(SpringJUnit4ClassRunner.class) //专用类运行器
@ContextConfiguration(classes = SpringConfig.class) //上下文配置
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testGetById() {
Book book = bookService.getById(1);
System.out.println(book);
}
@Test
public void testGetAll(){
List<Book> books = bookService.getAll();
System.out.println(books);
}
}
4.2表现层(controller)测试
![](https://i-blog.csdnimg.cn/blog_migrate/cabe642871accc714c2ac3a3168b136f.png)
5. 添加数据库事务
-
在jdbcConfig中加入平台事务管理类的代码
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
2.在BookService接口上方加入@Transactional
@Transactional
public interface BookService {
/**
* 保存
* @param book
* @return
*/
public boolean save(Book book);
/**
* 修改
* @param book
* @return
*/
public boolean update(Book book);
/**
* 删除
* @param id
* @return
*/
public boolean delete(Integer id);
/**
* 查找
* @param id
* @return
*/
public Book getById(Integer id);
/**
* 查询全部
* @return
*/
public List<Book> getAll();
}
3.SpringConfig中加入@EnableTransactionManagement
@Configuration
@ComponentScan("com.xlm.service")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
@EnableAspectJAutoProxy
@EnableTransactionManagement
public class SpringConfig {
}
6. 添加AOP来对功能进行运行时间测试
-
导包 aspectjweaver
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
-
SpringConfig中加入@EnableAspectJAutoProxy
3. 创建com.xxx.aop.ProjectAop类
@Component
@Aspect
public class ProjectAdvice {
//匹配业务层所有方法
@Pointcut("execution(* com.xlm.service.*Service.*(..))")
private void servicePt(){}
@Around("ProjectAdvice.servicePt()")
public void runSpeed(ProceedingJoinPoint pjp) throws Throwable {
Signature signature = pjp.getSignature();
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
pjp.proceed();
}
long end = System.currentTimeMillis();
System.out.println( signature.getName()+":"+"业务层接口万次执行时间为 "+ (end-start) + " ms");
}
}
7. 异常处理器
1.异常处理器的使用
在解决问题之前,我们先来看下异常的种类及出现异常的原因:
-
框架内部抛出的异常:因使用不合规导致
-
数据层抛出的异常:因外部服务器故障导致(例如:服务器访问超时)
-
业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写操作,导致索引异常等)
-
表现层抛出的异常:因数据收集、校验等规则导致(例如:不匹配的数据类型间导致异常)
-
工具类抛出的异常:因工具类书写不严谨不够健壮导致(例如:必要释放的连接长期未释放等)
在处理不同层的异常时,如果在每一层都添加异常处理,太麻烦,因此,遇见异常后均抛出,最后到表现层处理异常。——所有的异常均抛出到表现层处理
表现层处理异常,每个方法中单独书写,代码书写量巨大且意义不强 。 ——AOP
step1.由于异常交给表现层,可以在controller包中加入异常类(当然也可以放在别的包,但需要让springmvcconfig扫描到改类)
package com.xlm.controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//注意:如果不放在contoller包下,一定要让SpringMvcConfig扫描到该类所在的包,否则失败
@RestControllerAdvice //声明异常处理通知类
public class ProjectExceptionAdvice {
@ExceptionHandler(Exception.class) //拦截异方法(异常种类)
public Result doException(Exception ex){
System.out.println("嘿嘿!异常你往哪里去!");
return new Result(666,null,"怎么回事啊,咋出异常了!");
}
}
2.项目异常处理方案
异常处理器我们已经能够使用了,那么在咱们的项目中该如何来处理异常呢?
因为异常的种类有很多,如果每一个异常都对应一个@ExceptionHandler,那得写多少个方法来处理各自的异常,所以我们在处理异常之前,需要对异常进行一个分类:
-
业务异常(BusinessException)
-
规范的用户行为产生的异常
-
用户在页面输入内容的时候未按照指定格式进行数据填写,如在年龄框输入的是字符串
-
不规范的用户行为操作产生的异常
-
如用户故意传递错误数据
-
系统异常(SystemException)
-
项目运行过程中可预计但无法避免的异常
-
比如数据库或服务器宕机
-
其他异常(Exception)
-
编程人员未预期到的异常,如:用到的文件不存在
将异常分类以后,针对不同类型的异常,要提供具体的解决方案:
-
业务异常(BusinessException)
-
发送对应消息传递给用户,提醒规范操作
-
大家常见的就是提示用户名已存在或密码格式不正确等
-
系统异常(SystemException)
-
发送固定消息传递给用户,安抚用户
-
系统繁忙,请稍后再试
-
系统正在维护升级,请稍后再试
-
系统出问题,请联系系统管理员等
-
发送特定消息给运维人员,提醒维护
-
可以发送短信、邮箱或者是公司内部通信软件
-
记录日志
-
发消息和记录日志对用户来说是不可见的,属于后台程序
-
其他异常(Exception)
-
发送固定消息传递给用户,安抚用户
-
发送特定消息给编程人员,提醒维护(纳入预期范围内)
-
一般是程序没有考虑全,比如未做非空校验等
-
记录日志
step1.创建异常包和系统异常类和业务异常类
业务异常类
package com.xlm.exception;
public class BusinessException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = 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;
}
}
step2.创建系统类异常类
package com.xlm.exception;
public class SystempException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public SystempException(Integer code, String message) {
super(message);
this.code = code;
}
public SystempException( Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}
step3.添加异常编码(在Code类中)
package com.xlm.controller;
public class Code {
public static final Integer SAVE_OK = 20011; //业务成功编码
public static final Integer DELETE_OK = 20011;
public static final Integer UPDATE_OK = 20011;
public static final Integer GET_OK = 20011;
public static final Integer SAVE_ERR = 20010; //业务失败编码
public static final Integer DELETE_ERR = 20010;
public static final Integer UPDATE_ERR = 20010;
public static final Integer GET_ERR = 20010;
public static final Integer SYSTEM_ERR = 20010; //异常编码
public static final Integer BUSINESS_ERR = 20010;
}
step4.可以再功能中抛出异常,此处演示在BookServiceImpl类中抛出
public Book getById(Integer id) {
if (id == 0) {
throw new BusinessException(Code.BUSINESS_ERR,"请不要输入非法id来烦我!");
}
//将可能出现的异常进行包装,转换成自定义异常
try {
int i = 1/0;
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_ERR,"服务器访问超时,请重试!",e);
}
return bookDao.getById(id);
}
step5.拦截并处理异常(在先前创建的com.xlm.controller.ProjectExceptionAdvice类中)
package com.xlm.controller;
import com.xlm.exception.BusinessException;
import com.xlm.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//注意:如果不放在contoller包下,一定要让SpringMvcConfig扫描到该类所在的包,否则失败
@RestControllerAdvice //声明异常处理通知类
public class ProjectExceptionAdvice {
//1.系统异常
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex){
//1.记录日志
//2.发送消息给运维
//3.发送邮件给开发人员
return new Result(ex.getCode(),null,ex.getMessage());
}
//2.业务异常
@ExceptionHandler(BusinessException.class)
public Result doBusinessException(BusinessException ex){
return new Result(ex.getCode(),null, ex.getMessage());
}
//3.系统未知异常
@ExceptionHandler(Exception.class) //拦截异常方法(异常种类)
public Result doException(Exception ex){
return new Result(Code.BUSINESS_UNKNOWN_ERR,null,"系统繁忙,请稍后再试");
}
}
step6.查看结果
1.业务异常
![](https://i-blog.csdnimg.cn/blog_migrate/5fcf949897c71cf778e2860d57e1d43e.png)
2.系统异常
![](https://i-blog.csdnimg.cn/blog_migrate/d7327bfc8b3b1329b511a13e9b5000c4.png)
8.整合前端页面
step1.首先添加前端页面资源到webapp下,由于SpringMvc会拦截静态资源,因此需要添加 SpringMvcConfig类继承实现WebMvcConfigurationSupport类来防止静态资源被拦截。该类详解见文章http://t.csdn.cn/kS1Ld
package com.xlm.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@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/");
}
}
step2.在springmvcconfig中添加扫描
package com.xlm.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan({"com.xlm.controller","com.xlm.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
step3.准备前端工作
9.添加拦截器
-
拦截器概念
![](https://i-blog.csdnimg.cn/blog_migrate/045d81a3a9bdf84dca64c4946e6d0923.png)
(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的访问进行增强
![](https://i-blog.csdnimg.cn/blog_migrate/267a0e2dc24d2f1dc320ba59a8902066.png)
步骤1:创建拦截器类
让类实现HandlerInterceptor接口,重写接口中的三个方法。
@Component
//定义拦截器类,实现HandlerInterceptor接口
//注意当前类必须受Spring容器控制
public class ProjectInterceptorimplementsHandlerInterceptor {
@Override
//原始方法调用前执行的内容
public boolean preHandle(HttpServletRequestrequest, HttpServletResponseresponse, Objecthandler) throwsException {
System.out.println("preHandle...");
returntrue;
}
@Override
//原始方法调用后执行的内容
publi cvoid postHandle(HttpServletRequestrequest, HttpServletResponseresponse, Objecthandler, ModelAndViewmodelAndView) throwsException {
System.out.println("postHandle...");
}
@Override
//原始方法调用完成后执行的内容
public voida fterCompletion(HttpServletRequestrequest, HttpServletResponseresponse, Objecthandler, Exceptionex) throwsException {
System.out.println("afterCompletion...");
}
}
注意:拦截器类要被SpringMVC容器扫描到。
步骤2:配置拦截器类
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Autowired
private ProjectInterceptor projectInterceptor;
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
//配置拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books" );
}
}
步骤3:SpringMVC添加SpringMvcSupport包扫描
@Configuration
@ComponentScan({"com.itheima.controller","com.itheima.config"})
@EnableWebMvc
public class SpringMvcConfig{
}
步骤4:运行程序测试
使用PostMan发送http://localhost/books
如果发送http://localhost/books/100会发现拦截器没有被执行,原因是拦截器的addPathPatterns方法配置的拦截路径是/books,我们现在发送的是/books/100,所以没有匹配上,因此没有拦截,拦截器就不会执行。
步骤5:修改拦截器拦截规则
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Autowired
private ProjectInterceptor projectInterceptor;
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
//配置拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*" );
}
}
这个时候,如果再次访问http://localhost/books/100,拦截器就会被执行。
最后说一件事,就是拦截器中的preHandler方法,如果返回true,则代表放行,会执行原始Controller类中要请求的方法,如果返回false,则代表拦截,后面的就不会再执行了。
步骤6:简化SpringMvcSupport的编写
@Configuration
@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/*");
}
}
此后咱们就不用再写SpringMvcSupport类了。
最后我们来看下拦截器的执行流程:
当有拦截器后,请求会先进入preHandle方法,
如果方法返回true,则放行继续执行后面的handle[controller的方法]和后面的方法
如果返回false,则直接跳过后面方法的执行。