Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Interceptor does not execute for resource handler URLs

Tags:

spring-mvc

In the following setup, the TimingInterceptor and CORSHeaders interceptor execute on all URL requests, except for /resources/** URLs. How do I make the interceptors work for /resources/** URLs served by the ResourceHttpRequestHandler?

@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("/**");
    }

}
like image 397
tekumara Avatar asked Nov 21 '14 15:11

tekumara


1 Answers

Update: As of Spring Framework 5.0.1 (and SPR-16034), interceptors are automatically mapped on ResourceHttpRequestHandler by default.

I think the configured interceptors aren't mappped on the resource handler, but on the one handling @RequestMapping requests.

Maybe try this instead?

@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);
    }

}

This should be better documented with SPR-10655.

like image 83
Brian Clozel Avatar answered Nov 07 '22 21:11

Brian Clozel