- Interceptor在springboot2.x版本的快速入門
- 實現HandlerInterceptor的接口,並重載它的三個方法:preHandle、postHandle、afterCompletion。
-
1 1 /** 2 2 * 登陸攔截器 3 3 * @author HILL 4 4 * 5 5 */ 6 6 public class LoginInterceptor implements HandlerInterceptor { 7 7 8 8 @Override 9 9 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 10 10 throws Exception { 11 11 return HandlerInterceptor.super.preHandle(request, response, handler); 12 12 } 13 13 14 14 @Override 15 15 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 16 16 ModelAndView modelAndView) throws Exception { 17 17 HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); 18 18 } 19 19 20 20 @Override 21 21 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) 22 22 throws Exception { 23 23 HandlerInterceptor.super.afterCompletion(request, response, handler, ex); 24 24 } 25 25 }
2.加載過濾器的配置類,並設置過濾路徑路徑
這里的意思是:添加一個MyInterceptor攔截器,攔截路徑為/properties。(注意不要忘記在配置類上加@Configuration注解)

@Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/properties"); WebMvcConfigurer.super.addInterceptors(registry); } }
- 攔截器三個方法:preHandle、postHandle、afterCompletion的性質。
- 因為springboot就是類似一個配置好的ssm框架,所以mvc層就是springmvc,所以這里的性質也是一樣的。
preHandle:在進入controller之前進行攔截並決定是否放行。
postHandle:在controller處理完請求后,返回視圖前執行。當controller發生異常時不執行該方法。
afterCompletion:返回視圖后,一般用於資源的回收,因為發生異常該方法也會執行
- Interceptor的攔截性質
- 因為springmvc的入口就是dispatcherServlet,所有操作都是基於這個入口。所以Interceptor只能攔截springmvc中的RequestMapping,並不能攔截Servlet
- 需要攔截servlet時要定義filter進行過濾。
- 多個攔截器是的執行順序,preHandle是在configure類里先添加先執行。postHandle、afterCompletion則依次按順序由先進后出的規則執行。