自定义拦截器

    1. public class MyInterceptor implements HandlerInterceptor {
    2. private Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
    3. @Override
    4. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    5. logger.info("preHandle....");
    6. return true;
    7. }
    8. @Override
    9. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    10. logger.info("postHandle...");
    11. }
    12. @Override
    13. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    14. logger.info("afterCompletion...");
    15. }
    16. }

    注册拦截器

    1. @Configuration
    2. public class WebMvcConfig implements WebMvcConfigurer {
    3. @Override
    4. public void addInterceptors(InterceptorRegistry registry) {
    5. registry.addInterceptor(handlerInterceptor())
    6. //配置拦截规则
    7. .addPathPatterns("/**");
    8. }
    9. @Bean
    10. public HandlerInterceptor handlerInterceptor() {
    11. return new MyInterceptor();
    12. }
    13. }

    多个拦截器

    1. public void addInterceptors(InterceptorRegistry registry) {
    2. registry.addInterceptor(handlerInterceptor())
    3. .addPathPatterns("/**");
    4. registry.addInterceptor(handlerInterceptor2())
    5. .addPathPatterns("/**");
    6. }

    执行顺序

    image.png