SpringMVC4拦截器配置遇到的坑

目的:对get请求添加token验证(若为post请求可通过RequestBodyAdvice实现)。

情景:因为有api版本管理的需求,重写了WebMvcConfigurationSupport类的requestMappingHandlerMapping()方法,没有使用<mvc:annotation-driven/>标签,或@EnableWebMvc注解。

方案1:mvc的xml中配置mvc:interceptors标签,发现无论是设置全局还是特定请求拦截都没有生效。

方案2:类似springBoot中的拦截器设置,通过重写WebMvcConfigurerAdapter的addInterceptors方法实现,发现依然没有效果。

方案3:在继承的requestMappingHandlerMapping()方法中new出一个InterceptorRegistry,添加Interceptor后addInterceptors,setInterceptors,仍然无效。

最后,在继承WebMvcConfigurationSupport类时同时重写addInterceptors方法,终于成功。

问题暂时解决,但是xml中的配置没有用了吗?WebMvcConfigurerAdapter在SpringMVC4中也不好用?有时间需要阅读源码,探究调用关系。

posted on 2018-08-01 16:46  kurama2018  阅读(2066)  评论(0编辑  收藏  举报