天天看點

SpringMVC-添加攔截器1、MyInterceptor-定義一個攔截器2、WebMvcConfiguration-定義配置類,注冊攔截器

添加攔截器

  • 1、MyInterceptor-定義一個攔截器
  • 2、WebMvcConfiguration-定義配置類,注冊攔截器

攔截器不是一個普通屬性,而是一個類,是以就要用到java配置方式了。在SpringBoot官方文檔中有這麼一段說明:

  • 如果你想要保持Spring Boot 的一些預設MVC特征,同時又想自定義一些MVC配置(包括:攔截器,格式化器, 視圖控制器、消息轉換器 等等),你應該讓一個類實作WebMvcConfigurer,并且添加@Configuration注解。如果你想要自定義HandlerMapping、HandlerAdapter、ExceptionResolver等元件,你可以建立一個WebMvcRegistrationsAdapter執行個體 來提供以上元件。

總結:通過實作WebMvcConfigurer并添加@Configuration注解來實作自定義部分SpringMvc配置。

實作如下:

SpringMVC-添加攔截器1、MyInterceptor-定義一個攔截器2、WebMvcConfiguration-定義配置類,注冊攔截器

1、MyInterceptor-定義一個攔截器

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle method is running!");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle method is running!");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion method is running!");
    }
}
           

@Component

  • 在WebMvcConfiguration實作類中用到了@Autowired注解,被注解的這個類是從Spring容器中取出來的,那調用的這個類也需要被Spring容器管理,加上@Component把普通pojo執行個體化到spring容器中

2、WebMvcConfiguration-定義配置類,注冊攔截器

@Configuration
public class MvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private HandlerInterceptor myInterceptor;

    /**
     * 重寫接口中的addInterceptors方法,添加自定義攔截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }
}