MVC Java Config - HandlerInterceptor not excluding paths

solarwind picture solarwind · Nov 27, 2013 · Viewed 16.8k times · Source

I have a MVC Java configuration but the HandlerInterceptor is not excluding some patterns.

At the line marked with xxx, if

1) I add both addPatterns("/**") and excludePathPatterns("*.ecxld") to the HandlerInterceptor's InterceptorRegistration, the HandlerInterceptor.preHanlde() is NOT invoked at all. e.g .addPathPatterns("/**").excludePathPatterns("*.ecxld")

2) I add only excludePathPatterns("*.ecxld") to the HandlerInterceptor's InterceptorRegistration, the HandlerInterceptor.preHanlde() is still executed.

(the other interceptors are invoked fine).

Any pointers appreciated.

Thanks

@Configuration
public class MyMVCConfigurerAdapter extends WebMvcConfigurerAdapter {

 @Override
 public void addInterceptors(final InterceptorRegistry registry) {

     registry.addInterceptor(getInterceptorOne());

     registry.addInterceptor(getMyHandlerInterceptor())
                 .excludePathPatterns("*.ecxld");  // **xxx**

     registry.addInterceptor(getInterceptorTwo()
     );

 }

Answer

M. Deinum picture M. Deinum · Nov 27, 2013

The patterns you specify for include and exclude are ant bases path expressions and not normal URL expressions as you would express in web.xml to map a servlet or filter for instance.

To make an exclude work you have to also include an include path (as you already noticed with your second remark). Next change your exclude pattern to /**/*.ecxld.

Your current expression *.ecxld would match file.ecxld but it will not match /file.ecxld or even /foo/file.ecxld. The /**/ part takes care of that. However to make it work it also requires an includePathExpression (the code checks if there is an includePathExpression when not it is ignoring the excludePathExpression).

So in short change your configuration to the following should solve your problem.

@Configuration
public class MyMVCConfigurerAdapter extends WebMvcConfigurerAdapter {

 @Override
 public void addInterceptors(final InterceptorRegistry registry) {

     registry.addInterceptor(getInterceptorOne());

     registry.addInterceptor(getMyHandlerInterceptor())
                 .includePathPatterns("/**")
                 .excludePathPatterns("/**/*.ecxld");  

     registry.addInterceptor(getInterceptorTwo()
     );

 }