I use the "HandlerInterceptor" to set some attributes to "request" at the invocation of each controller and check the URL parameters. I would like to easily exclude this interceptor from all static resources. For various reasons (including the migration of the application from another framework), I have static resources placed in several folders.

Currently I have to do it this way:

@Configuration
public class WebAppConfigExample implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/packed/**","/app/img/**","/app/css/**");
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    InterceptorRegistration r = registry.addInterceptor(new HandlerInterceptor() {
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         request.setAttribute("some_specific_attribute", "value");
         if (request.getParameter("param") != null) {
           // do something
         }
         // other operations on request, 
         // or response.sendRedirect is some cases
         return true;
      }
    });
    r.addPathPatterns("/**");

    //  Here "excludeStaticResources" method would be very helpful!
    r.excludePathPatterns("/packed/**","/app/img/**","/app/css/**");

  }

}

It would be very useful to have an excludeStaticResources() or excludeResource() method in InterceptorRegistration, so that I don't have to repeat the list of folders with static resources. Or the includeControllersOnly method, which would set the Interceptor exclusively for MVC Spring controllers.

Comment From: aditya78910

can i try contribute?

Comment From: aditya78910

I was exploring how we can provide an option to the developer to configure a HandlerInterceptor which will be invoked only for all RestControllers. One way, this can be achieved is by checking the type of the handler (whether it is RestController annotated).

The option to configure this can be added in the InterceptorRegistration and then at runtime we can add the related mappedinterceptor to the handlerexecutionchain accordingly depending on the handler being ( RestController annotated). We can do this by introducing a check in the MappedInterceptor here

Requesting the esteemed advice and feedback from the spring team if this thinking is in logical direction.

Comment From: bclozel

I have looked into this topic and think that the current solution described in the original post is quite good. In this case, you would like to ignore ResourceHttpRequestHandler, but there are other implementations of WebContentGenerator or handlers producing RSS, sitemap documents, etc - that still might qualify as ignored by your interceptor.

I think that excluding by path patterns makes a lot of sense here, as we can't check against all possible implementations here.