4.拦截器
4.1拦截器概述
- 概述:一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行
- 实际开发中,静态资源(HTML/CSS)不需要交给框架处理,需要拦截的是动态资源
4.2图示
-
图示
4.3案例实现
-
模拟没有登录拦截操作
-
新定义拦截器
@Component public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("登录拦截操作");String username = request.getParameter("username");if("sy".equals(username)){return true;}System.out.println("preHandle");return false;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("postHandle");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("afterCompletion");} }
-
修改SpringMvc 配置
@Configuration @ComponentScan({"cn.sycoder.controller","cn.sycoder.interceptor"}) @EnableWebMvc public class SpringMvcConfig implements WebMvcConfigurer {@AutowiredLoginInterceptor loginInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginInterceptor).addPathPatterns("/item","/item/*");} }
-
controller 确实被拦截
@RestController @RequestMapping("/item") public class ItemController {@GetMapping("/{id}")public String getById(@PathVariable Long id){return "query"+id;}@GetMappingpublic String list(){return "list";} }
4.4拦截器参数讲解
- HttpServletRequest request
- HttpServletResponse response
- Object handler 相当于是对访问接口的一种包装
4.5拦截器链
-
新增拦截器
@Component public class AuthInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("权限拦截的方法");return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("权限拦截的postHandle方法");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("权限拦截的afterCompletion方法");} }
-
添加到拦截器链中
@Configuration @ComponentScan({"cn.sycoder.controller","cn.sycoder.interceptor"}) @EnableWebMvc public class SpringMvcConfig implements WebMvcConfigurer {@AutowiredLoginInterceptor loginInterceptor;@AutowiredAuthInterceptor authInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginInterceptor).addPathPatterns("/item","/item/*");registry.addInterceptor(authInterceptor).addPathPatterns("/item","/item/*");} }
-
拦截器链注意点
- 拦截器有着先进后出的原则
- preHandle : 与配置顺序保持一致的执行顺序
- postHandle:与配置顺序相反,可能不运行
- afterCompletion:与配置顺序相反,可能不运行
4.6面试题拦截器与过滤器的区别
-
区别
- 技术所属不同
- 过滤器:Servlet 技术
- 拦截器:SpringMVC技术
- 拦截内容不同
- Filter : 是对所有访问进行过滤
- Interceptor:仅仅针对访问SpringMVC
- 技术所属不同
-
访问流程