1、拦截器注册类,按照注册顺序,先注册,先拦截。
在2.x之前,实现WebMvcConfigurationAdapter
@Configuration
public class MyInterceptorConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/demo/**");
WebMvcConfigurer.super.addInterceptors(registry);
}
}
自定义拦截器
public class MyInterceptor implements HandlerInterceptor {
// 进入Controller方法之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("MyInterceptor -- preHandle");
return HandlerInterceptor.super.preHandle(request, response, handler);
}
// 调用完Controller之后,视图渲染之前,如果Controller出现异常,将不会执行
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor -- postHandle");
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
// 整个完成之后,通常用于资源清理,不管有没有异常
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("MyInterceptor -- afterCompletion");
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}