Affects: 6.2.0
If register an Interceptor in InterceptorRegistration and call addPathPatterns() or excludePathPatterns(), the Interceptor becomes a MappedInterceptor.
The existing MappedInterceptor operates based on URL matching.
@Configuration
@RequiredArgsConstructor
public class InterceptorConfig implements WebMvcConfigurer {
private final ItemsInterceptor itemsInterceptor;
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(itemsInterceptor)
.addPathPatterns("/items"); // Want to intercept only DELETE /items. But it intercepts all methods.
}
}
However, servers that use Restful API sometimes use different HttpMethods for the same URL.
Example: GET /items/{id} and DELETE /items/{id}
However, since MappedInterceptor is a URL-based operation, the determination of HttpMethod and URL should be done within the Interceptor implementation.
@Component
@Slf4j
public class ItemsInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) {
// pass when request is GET /items
if (request.getMethod().equals("GET") && request.getRequestURI().equals("/items")) {
return true;
}
// do something when request is not GET /items
log.info("ItemsInterceptor preHandle");
return false;
}
}
However, I think that only the code related to the "function" that the Interceptor will perform should be included in the Interceptor, and the registration and configuration of the Interceptor should be done in InterceptorRegistration.
So I planned to create a way to add an interceptor based on URL and HttpMethod, and the work is progressing to some extent.
If there is a positive evaluation of my plan, I will create a Pull Request after the work is fully completed.
Comment From: bclozel
Thanks for the proposal but I believe path mapping for interceptors is meant as a way to better separate concerns. If you would like to selectively apply an interceptor, you should do that directly in the implementation of the interceptor as it receives the http request as an argument.
We do not intend to extend the handler interceptor model in this fashion. I'm closing this issue as a result. Thanks.