Spring MVC Interceptor不会为资源处理程序URL执行

时间:2014-11-21 15:53:49

标签: spring-mvc

在以下设置中,TimingInterceptor和CORSHeaders拦截器对所有URL请求执行,但/ resources / ** URL除外。如何使拦截器适用于ResourceHttpRequestHandler服务的/ resources / ** URL?

@EnableWebMvc //equivalent to mvc:annotation-driven
@Configuration 
@PropertySource("classpath:configuration.properties") 
public class WebConfig extends WebMvcConfigurerAdapter {

    @Inject
    private TimingInterceptor timingInterceptor;

    @Inject
    private CORSHeaders corsHeaders;

    // equivalent to mvc:resources
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");

    }

    // equivalent to mvc:interceptors
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timingInterceptor).addPathPatterns("/**");
        registry.addInterceptor(corsHeaders).addPathPatterns("/**");
    }

}

2 个答案:

答案 0 :(得分:2)

更新:从Spring Framework 5.0.1(和SPR-16034)开始,默认情况下,拦截器会自动映射到ResourceHttpRequestHandler

我认为配置的拦截器不是在资源处理程序上映射,而是在处理@RequestMapping请求的拦截器上。

也许试试这个?

@EnableWebMvc //equivalent to mvc:annotation-driven
@Configuration 
@PropertySource("classpath:configuration.properties") 
public class WebConfig extends WebMvcConfigurerAdapter {

    @Inject
    private TimingInterceptor timingInterceptor;

    @Inject
    private CORSHeaders corsHeaders;

    // equivalent to mvc:resources
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");

    }

    @Bean
    public MappedInterceptor timingInterceptor() {
        return new MappedInterceptor(new String[] { "/**" }, timingInterceptor);
    }

    @Bean
    public MappedInterceptor corsHeaders() {
        return new MappedInterceptor(new String[] { "/**" }, corsHeaders);
    }

}

SPR-10655应该更好地记录下来。

答案 1 :(得分:0)

我从未尝试过使用Spring拦截器来提供资源。拦截器的强大之处在于在控制器之前以及在控制器和视图之间有一个 hook

要围绕资源添加预处理或后处理,最好使用过滤器。