内容:继承HandlerInterceptorAdapter并实现WebMvcConfigurer,拦截器中的方法将preHandle->Controller->postHandle->affterCompletion的顺序执行。
注意:只有preHandle方法返回true时后面的方法才会执行。当拦截器链存在多个拦截器时,postHandle在所有拦截器内的所有拦截器返回成功时才会调用,而affterCompletion只有preHandle返回true才调用,但如果拦截器内的第一个拦截器的preHandle方法返回false,后面的方法都不会执行。
@Componentpublic class AppInterceptor extends HandlerInterceptorAdapter implements WebMvcConfigurer{@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("preHandle执行");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执行");}//设置拦截路径配置,addPathPatterns为拦截的路径,excludePathPatterns为排除的路径
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TestInterceptor())
.addPathPatterns(“/**”)
.excludePathPatterns(“/hello1”);}
}