基本概念
拦截器的作用
Spring MVC 的拦截器类似于 Servlet 开发中的过滤器 Filter,用于对处理器进行预处理和后处理。
将拦截器按一定的顺序联结成一条链,这条链称为拦截器链(Interceptor Chain)。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用。拦截器也是AOP思想的具体实现。
拦截器的方法
拦截器和过滤器的区别
拦截器的创建
自定义拦截器的创建只需要如下三步:
① 创建拦截器类实现HandlerInterceptor接口 ② 配置拦截器 ③ 测试拦截器的拦截效果
拦截器的创建
以完成一个案例的形式进行展示
题目要求:
创建拦截器,拦截所有请求,在每个请求访问Controller前在控制台输出一句“博主最帅!!!”😁。
项目构建
项目为SpringBoot项目,目录结构如下:
controller
package com.xxx.interceptor02.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @RequestMapping("/c01") public String controller01(){ System.out.println("我是controller01"); return "我是controller01"; } @RequestMapping("/c02") public String controller02(){ System.out.println("我是controller02"); return "我是controller02"; } @RequestMapping("/c03") public String controller03(){ System.out.println("我是controller03"); return "我是controller03"; } }
interceptor
package com.xxx.interceptor02.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //登陆检查 //1、配置好拦截器要拦截哪些请求 //2、把这些配置放在容器中 public class MyInterceptor implements HandlerInterceptor { //目标方法执行之前 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("博主最帅!!!"); return true;//放行 } //目标方法执行完成以后 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { //HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } //页面渲染以后 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { //HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } }
config(注册拦截器)
packpackage com.xxx.interceptor02.config; import com.xxx.interceptor02.interceptor.MyInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyWebConfig implements WebMvcConfigurer {//实现WebMvcConfigurer @Override public void addInterceptors(InterceptorRegistry registry) { // registry.addInterceptor(new MyInterceptor()) registry.addInterceptor(myInterceptor())//注册拦截器 .addPathPatterns("/**");//拦截所有请求 } @Bean public MyInterceptor myInterceptor(){//创建拦截器 return new MyInterceptor(); } }
效果展示
访问如下url
控制台输出如下信息