Spring boot 配置自己的拦截器
框架使用的是spring boot 2.0
首先,自定义拦截器实现HandlerInterceptor接口,preHandler是在执行controller方法前执行的 此外还有两个方法,具体作用最后才说,先熟悉以下拦截器的使用流程。
1 @Component 2 public class PassportInterceptor implements HandlerInterceptor{ 3 4 @Override 5 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 6 throws Exception { 7 HttpSession session = request.getSession(); 8 User user = (User)session.getAttribute("user"); 9 if(user == null) { 10 response.sendRedirect("/login"); 11 return false; 12 } 13 return true; 14 } 15 16 }
上面拦截器只是简单的通过session验证是否登录
定义了自己的拦截器后就要实现 WebMvcConfigurer接口 注:该接口好像是spring boot 2.0以后有的 之前不是这个接口 该接口提供了方法添加拦截器,加上@Component注解 让其能被ioc容器管理
1 @Component 2 public class LabWebConfiguration implements WebMvcConfigurer{ 3 4 @Autowired 5 PassportInterceptor passportInterceptor; 6 7 @Override 8 public void addInterceptors(InterceptorRegistry registry) { 9 10 registry.addInterceptor(passportInterceptor) 11 .addPathPatterns("/**") 12 .excludePathPatterns("/stylesheets/**", "/javascripts/**","/fonts/**", 13 "/images/**", "/login/**", "/regist/**"); 14 } 15 16 17 }
registry有三个重要的方法,addInterceptors()方法将自定义的拦截器添加进去 addPathPatterns 方法的主要作用是添加拦截器要拦截的路径,excludePathPatterns的功能则是配置对某些路径放行。上面我针对自己的静态资源、还有登录注册页面放行
接下来做一个小小的测试 测试以下拦截器各个方法的执行顺序
1 @Controller 2 public class TestController { 3 4 @RequestMapping("/test") 5 @ResponseBody 6 public String testInterceptor() { 7 8 System.out.println("Controller方法执行"); 9 10 return "test"; 11 } 12 13 }
1 @Component 2 public class TestInterceptor implements HandlerInterceptor{ 3 4 @Override 5 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 6 throws Exception { 7 System.out.println("preHandler执行了"); 8 return true; 9 } 10 @Override 11 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 12 ModelAndView modelAndView) throws Exception { 13 System.out.println("postHandler执行了"); 14 } 15 @Override 16 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) 17 throws Exception { 18 // TODO Auto-generated method stub 19 System.out.println("afterCompletion执行了"); 20 } 21 22 }
1 @Component 2 public class LabWebConfiguration implements WebMvcConfigurer{ 3 @Autowired 4 TestInterceptor testInterceptor; 5 6 @Override 7 public void addInterceptors(InterceptorRegistry registry) { 8 registry.addInterceptor(testInterceptor) 9 .addPathPatterns("/test"); 10 } 11 12 13 }
结果如下
可见preHander方法只在Controller执行前 return true则放行
postHandler则是在 具体的Controller方法执行后执行
afterCompletion 看资料说是在页面渲染完成后执行 因此可以用来作为资源的清理工作