SpringBoot - 自定义拦截器
1.定义拦截器只需要实现HandlerIntercepter
/** * 自定义拦截器 */ public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("====在该方法执行之前执行===="); // 返回true才会继续执行,返回false则取消当前请求 return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("执行完方法之后进执行(Controller方法调用之后),但是此时还没进行视图渲染"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("整个请求都处理完咯,DispatcherServlet也渲染了对应的视图咯,此时我可 以做一些清理的工作了"); } }
2.注册自定义拦截器
@Configuration(proxyBeanMethods=true) public class AppConfig { @Bean public WebMvcConfigurer webMvcConfigurer(){ return new WebMvcConfigurer() { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()) .addPathPatterns("/**") //要拦截的请求 .excludePathPatterns("/","/index","/css/**","/js/**");//不拦截的请求 } }; } }