SpringMVC添加拦截器Interceptor(二)

如何添加Interceptor

实现接口 WebMvcConfigurer 并重写方法 addInterceptors

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
                System.out.println("Interceptor: HandlerInterceptor preHandle 执行目标方法是:" + handler);
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
                System.out.println("Interceptor: HandlerInterceptor postHandle 执行,视图名称是:" + modelAndView);
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
                System.out.println("Interceptor: HandlerInterceptor afterCompletion 执行,查看异常:" + ex);
            }
        });
    }
}
  • preHandle 在目标方法执行之前调用,可以对目标方法进行拦截,阻止继续执行
  • postHandle 在目标方法执行之后,视图渲染之前执行,可以对 ModelAndView 进行获取或操作
  • afterCompletion 在视图渲染之后执行,可以获取异常
Interceptor: HandlerInterceptor preHandle 执行目标方法是:com.rick.spring.mvc.InterceptorTestApplication#index()
Interceptor: HandlerInterceptor postHandle 执行,视图名称是:ModelAndView [view="index"; model={}]
Interceptor: HandlerInterceptor afterCompletion 执行,查看异常:null

github地址:https://github.com/jkxyx205/spring-boot-learn/tree/master/spring-mvc-inteceptor