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 exa
I think in spring-boot 2.0 version, this have changed a lot right now. Below is the implementation you can easily add and configure the path pattern.
@Component
public class ServiceRequestAppConfig implements WebMvcConfigurer {
@Autowired
ServiceRequestInterceptor sri;
@Override
public void addInterceptors(InterceptorRegistry registry) {
String pathPattern = "/admin/**";
registry.addInterceptor(sri).excludePathPatterns(pathPattern);
}
}
@Component
public class ServiceRequestInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// Your logic
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex){
// Some useful techniques
}
}
In my case:
/api/v1/user-manager-service/tenants/add
there was incorrect PathPattern configuration:
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/tenants/**");
}
I was missing:
/**
before actual path.
After correction it works as expected:
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/**/tenants/**");
}
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>