Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC 3, Interceptor on all excluding some defined paths

Is it possible to apply an interceptor to all controllers and actions, except some that are defined?

Just to be clear, I am not interested in applying an interceptor on a list of defined ones. I want to define those to exclude.

Thanks!

like image 996
mjs Avatar asked Mar 28 '12 13:03

mjs


3 Answers

Since Spring 3.2 they added that feature with the tag

mvc:exclude-mapping

See this example from the Spring documentation:

<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
<mvc:interceptor>
    <mvc:mapping path="/**"/>
    <mvc:exclude-mapping path="/admin/**"/>
    <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" />
</mvc:interceptor>
<mvc:interceptor>
    <mvc:mapping path="/secure/*"/>
    <bean class="org.example.SecurityInterceptor" />
</mvc:interceptor>

Here's the link to the doc

like image 186
gamerkore Avatar answered Nov 18 '22 23:11

gamerkore


For java based configuration, from the docs

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LocaleInterceptor());
        registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
        registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
    }

}
like image 42
Abdullah Khan Avatar answered Nov 18 '22 23:11

Abdullah Khan


When configuring an interceptor, you can specify a path pattern. The interceptor will be invoked only for controllers which the path matches the interceptor path pattern.

ref: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config-interceptor

But as you probably noticed it, the path pattern doesn't support exclusion.

So I think the only way is to code a blacklist of paths inside the interceptor. When the interceptor is invoked, retrieve the HttpServletRequest.getRequestURI() and check if the path is blacklisted or not.

You can build the blacklist inside a @PostConstruct annotated method of the interceptor, and so get the blacklisted path from a property file for instance.

like image 3
tbruyelle Avatar answered Nov 18 '22 21:11

tbruyelle