Appearance
1.拦截器概述
- 拦截器是一种动态拦截方法调用的机制,在 SpringMVC 中动态拦截控制器方法的执行
- 作用:
- 在指定的方法调用前后执行预先设定的代码
- 阻止原始方法的执行
2.拦截器和过滤器的区别
- 归属不同:Filter 属于 Servlet 技术,Interceptor属于 SpringMVC 技术。
- 拦截内容不同:Filter 对所有访问进行增强,Interceptor 仅对 SpringMVC 的访问进行增强。
3.拦截器开发
- 创建拦截器类,实现 HandlerInterceptor 接口
java
@Component
public class ProjectInterceptorr implements HandlerInterceptor {
//原始方法调用前执行的内容
@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......");
}
}
- 配置拦截器类
java
@Configuration
public class SpringSupport extends WebMvcConfigurationSupport {
@Autowired
private ProjectInterceptorr projectInterceptorr;
//拦截器
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(projectInterceptorr).addPathPatterns("/books","/books/*");
}
}
- SpringMVC 包扫描
java
@Configuration
@ComponentScan({"com.my.controller","com.my.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
4.拦截器的执行流程
==

5.拦截器链配置
1.配置多个拦截器
- 创建拦截器类
java
@Component
public class ProjectInterceptorr2 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle2......");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle2......");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion2......");
}
}
- 配置拦截器类
java
@Configuration
public class SpringSupport extends WebMvcConfigurationSupport {
@Autowired
private ProjectInterceptorr projectInterceptorr;
@Autowired
private ProjectInterceptorr2 projectInterceptorr2;
//拦截器
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(projectInterceptorr).addPathPatterns("/books","/books/*");
registry.addInterceptor(projectInterceptorr2).addPathPatterns("/books","/books/*");
}
}
2.拦截器链的执行
- 拦截器的执行顺序和配置顺序有关,先进先出。
- 拦截器链的运行顺序参照拦截器添加顺序为准
- 当拦截器链出现对原始处理器的拦截,后面的拦截器终止运行
- 当拦截器运行中断,仅运行配置走在前面的拦截器的 afterCompletion 操作