Spring MVC Interceptor does not execute resource handler URLs

In the following setup, the TimingInterceptor and CORSHeaders interceptor runs on all URLs except URL / resources / **. How to make interceptors work for / resources / ** URLs served by 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("/**"); } } 
+5
source share
2 answers

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

I think that the configured interceptors are not displayed on the resource handler, but on a single @RequestMapping .

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 .

+2
source

I have never tried using Spring interceptors to serve resources. Interceptor power is the capture in front of the controller and between the controller and the view.

To add before or after processing resources, it is better to use filters.

0
source

Source: https://habr.com/ru/post/1207418/


All Articles