- 前言
- 拦截器
- 介绍
- 具体实现
- 1.新建项目
- 2.MyInterceptor01.java
- 3.配置拦截器
- 4.InterceptorController.java
- 5.测试
- 多个拦截器的执行顺序
- 1.MyInterceptor01.java
- 2.MyInterceptor02.java
- 3.MyWebMvcConfigurer.java
- 4.测试
拦截器(Interceptor)主要是针对特定处理器进行拦截的。也就是说它拦截的对象是我们的Controller请求。我们可以将Controller中的通用代码进行抽取放在拦截器中,就这一点来讲功能跟我们之前讲的AOP类似(Interceptor底层就是利用AOP来实现的)。在实际开发中Interceptor通常用来做权限校验(现在都有成熟的权限校验框架。比如轻量级的Shiro,还有Spring推出的Spring Security )
拦截器 介绍拦截器(Interceptor)实现对每一个请求处理前后进行相关的业务处理,类似与servlet中的Filter。
SpringMVC 中的 Interceptor 拦截请求是通过 HandlerInterceptor 接口来实现的。
拦截器可以通过以下几种方式进行实现:
-
实现 SpringMVC 的 HandlerInterceptor 接口;
-
继承实现了 HandlerInterceptor 接口的类,比如 SpringMVC 已经提供的实现了HandlerInterceptor 接口的抽象类 HandlerInterceptorAdapter;
-
实现 SpringMVC 的 WebRequestInterceptor 接口;
-
继承实现了 WebRequestInterceptor 的类;
在上一节SpringBoot.11.IDEA中如何快速复制当前父项目中的一个Module为新的项目中我们已经准备好了Module – springboot-08-interceptor。如下图所示:
package com.christy.config.interceptors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor01 implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(MyInterceptor01.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("==========MyInterceptor01==========handler=========" + handler);
log.info("==========MyInterceptor01==========preHandle=========");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("==========MyInterceptor01==========postHandle=========");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("==========MyInterceptor01==========ex========={}", ex);
log.info("==========MyInterceptor01==========afterCompletion=========");
}
}
3.配置拦截器
我们进入到MyWebMvcConfigurer.java中,按快捷键Alt+Insert,选择Implement Methods…或者直接按快捷键Alt+Shift+P。如下图所示:
在Select Methods to Implement中选择addIntefceptors()这个方法。如下图所示:
修改MyWebMvcConfigurer.java内容如下所示:
import com.christy.config.interceptors.MyInterceptor01;
import com.christy.constants.FileConstants;
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.WebMvcConfigurer;
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor01())
.addPathPatterns("/interceptor
String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith("win")){
// Windows虚拟路径映射本地磁盘
registry.addResourceHandler(FileConstants.fileVirtualPath + "**").addResourceLocations("file:" + FileConstants.fileWindowsPath);
} else {
// Linux虚拟路径映射本地磁盘
registry.addResourceHandler(FileConstants.fileVirtualPath + "**").addResourceLocations("file:" + FileConstants.fileLinuxPath);
}
}
}
4.InterceptorController.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/interceptor")
public class InterceptorController {
private static final Logger log = LoggerFactory.getLogger(InterceptorController.class);
@RequestMapping("sayHello")
public String sayHello(){
log.info("Hello Interceptor…");
return "interceptor";
}
}
5.测试
启动项目,浏览器访问http://localhost:8808/interceptor/sayHello,注意观察页面和控制台输出:
我们改造一下sayHello()方法抛出一个异常,如下所示:
@RequestMapping("sayHello")
public String sayHello(){
log.info("Hello Interceptor…");
int i = 1/0;
return "interceptor";
}
重新启动项目,浏览器访问http://localhost:8808/interceptor/sayHello,注意观察页面和控制台输出:
我们修改一下MyInterceptor01.java如下:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor01 implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(MyInterceptor01.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("==========MyInterceptor01==========1=========");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("==========MyInterceptor01==========2=========");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("==========MyInterceptor01==========3=========");
}
}
2.MyInterceptor02.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor02 implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(MyInterceptor02.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("==========MyInterceptor02==========4=========");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("==========MyInterceptor02==========5=========");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("==========MyInterceptor02==========6=========");
}
}
3.MyWebMvcConfigurer.java
import com.christy.config.interceptors.MyInterceptor01;
import com.christy.config.interceptors.MyInterceptor02;
import com.christy.constants.FileConstants;
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.WebMvcConfigurer;
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor01())
.addPathPatterns("/interceptor
String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith("win")){
// Windows虚拟路径映射本地磁盘
registry.addResourceHandler(FileConstants.fileVirtualPath + "**").addResourceLocations("file:" + FileConstants.fileWindowsPath);
} else {
// Linux虚拟路径映射本地磁盘
registry.addResourceHandler(FileConstants.fileVirtualPath + "**").addResourceLocations("file:" + FileConstants.fileLinuxPath);
}
}
}
4.测试
重新启动项目,浏览器访问http://localhost:8808/interceptor/sayHello,注意观察控制台输出:
多个拦截器注册以后按照注册的顺序以栈式结构存储,上面我们配置了两个拦截器,MyInterceptor01先入栈,MyInterceptor02后入栈;所以当请求来了之后:
首先,进入MyInterceptor01的preHandle打印输出1,再进入MyInterceptor02的preHandle打印输出4;这是一个入栈的过程
其次访问方法主体打印输出方法体内的logger
然后,进入MyInterceptor02的postHandle打印输出5,再进入MyInterceptor01的postHandle打印输出2;这是一个出栈的过程
最后,进入MyInterceptor02的afterCompletion打印输出6,再进入MyInterceptor01的afterCompletion打印输出3;这也是一个出栈的过程
按照上面的描述如果我们更换两个拦截器的顺序,让MyInterceptor02先入栈,MyInterceptor01后入栈;那么打印的结果应该是4->1->2->5->3->6。
我们修改MyWebMvcConfigurer.java的代码更换两个拦截器的顺序如下:
import com.christy.config.interceptors.MyInterceptor01;
import com.christy.config.interceptors.MyInterceptor02;
import com.christy.constants.FileConstants;
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.WebMvcConfigurer;
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor01())
.addPathPatterns("/interceptor
String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith("win")){
// Windows虚拟路径映射本地磁盘
registry.addResourceHandler(FileConstants.fileVirtualPath + "**").addResourceLocations("file:" + FileConstants.fileWindowsPath);
} else {
// Linux虚拟路径映射本地磁盘
registry.addResourceHandler(FileConstants.fileVirtualPath + "**").addResourceLocations("file:" + FileConstants.fileLinuxPath);
}
}
}
然后重启项目,浏览器访问http://localhost:8808/interceptor/sayHello,注意观察控制台输出:



