创建拦截器TestInterceptor.java
@Component public class TestInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return HandlerInterceptor.super.preHandle(request, response, handler); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } }
在WebMvc配置类添加拦截器
@Configuration public class WebMvcConf extends WebMvcConfigurationSupport { /** rest接口过滤排除 */ String[] TEST_EXCLUDE_PATHS = { "/test/login/*" }; @Autowired TestInterceptor testInterceptor; /** * 拦截器配置 */ @Override public void addInterceptors(InterceptorRegistry registry) { // 手动获取spring管理的bean (这是没有必要的) // HandlerInterceptor testInterceptor = (HandlerInterceptor) getApplicationContext().getBean("testInterceptor"); // 跨域请求的OPTIONS请求处理 registry.addInterceptor(testInterceptor) .addPathPatterns("/**") // 拦截器拦截路径 .excludePathPatterns(TEST_EXCLUDE_PATHS); // 不需要拦截的路径 super.addInterceptors(registry); } }
手动获取bean是为了,如果在拦截器中需要调用其它spring管理的service等,直接注解形式的拦截器会获取不到,所以改成在WebMvcConf中手动添加的形式,这种形式也可以灵活的控制拦截路径和不需要拦截的路径,比较清晰;
==========2019-05-14==========
其实上面的说法并不对,继承WebMvcConfigurationSupport的方式可行,但是会覆盖掉很多默认的配置,只能同时存在一个。所以现在采用实现WebMvcConfigurer接口的方式来分离出每个配置,每种配置放在单独的类里更加清晰,例如上面的拦截器现在的实现方式是
@Configuration public class InterceptorConf implements WebMvcConfigurer { /** rest接口过滤排除 */ String[] TEST_EXCLUDE_PATHS = { "/test/login/*" }; @Autowired TestInterceptor testInterceptor; /** * 拦截器配置 */ @Override public void addInterceptors(InterceptorRegistry registry) { // 跨域请求的OPTIONS请求处理 registry.addInterceptor(testInterceptor) .addPathPatterns("/**") // 拦截器拦截路径 .excludePathPatterns(TEST_EXCLUDE_PATHS); // 不需要拦截的路径 } }
Interceptor已经添加了@Component
注解,可以直接使用@Autowired
,使用spring管理,更加方便了其实。
留言