Issue
I know we can map different url to different interceptor, or we can map multiple url to single interceptor too. I am just curious to know if we also have exclude option. for example if I have 50 url mapping in application and except 1 mapping I want to call interceptor for all so rather than writing configuration for 49 mapping can I just mention * and one exclude to the 50th url?
Solution
HandlerInterceptor
s can be applied or excluded to (multiple) specific url's or url-patterns.
See the MVC Interceptor Configuration.
Here are the examples from the documentation
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleInterceptor());
registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
// multiple urls (same is possible for `exludePathPatterns`)
registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*", "/admin/**", "/profile/**");
}
}
or using XML config
<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>
<!-- intercept multiple urls -->
<mvc:mapping path="/secure/*"/>
<mvc:mapping path="/admin/**"/>
<mvc:mapping path="/profile/**"/>
<bean class="org.example.SecurityInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
Answered By - fateddy
Answer Checked By - Candace Johnson (JavaFixing Volunteer)