I have a Spring 3 Web App that implements two interceptors. Im using a config class annotated @Configuration. The code is as follows:
@Override
public void addInterceptors(InterceptorRegistry registry) {
// TODO Auto-generated method stub
super.addInterceptors(registry);
registry.addInterceptor(homeInterceptor()).addPathPatterns("/");
registry.addInterceptor(allInterceptor());
}
No matter what order I add the interceptors to the registry, the allInterceptor's preHandle function is always called before the homeInterceptor's preHandle. Does anyone know how to control the order that interceptors are invoked?
Thanks!
React Full Stack Web Development With Spring Boot To work with interceptor, you need to create @Component class that supports it and it should implement the HandlerInterceptor interface. preHandle() method − This is used to perform operations before sending the request to the controller.
prehandle() – called before the execution of the actual handler. postHandle() – called after the handler is executed. afterCompletion() – called after the complete request is finished and the view is generated.
It is a Java class which is executed by the servlet container for each incoming HTTP request and for each HTTP response. Requests always first pass through Filter instances, before reaching a Servlet.
Spring Interceptor are used to intercept client requests and process them. Sometimes we want to intercept the HTTP Request and do some processing before handing it over to the controller handler methods. That's where Spring MVC Interceptor come handy.
I looked at the underlying implementation, the global interceptors(not associated to any path mapping) get executed before the mapped interceptors (with associated path patterns). So if you want the homeInterceptor
to be executed before the allInterceptor
, the allInterceptor
may have to be made a mapped interceptor(by providing a path pattern).
These are the two methods that record the interceptors and find the interceptors at runtime:
org.springframework.web.servlet.handler.AbstractHandlerMapping.initInterceptors()
org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandlerExecutionChain(Object, HttpServletRequest)
It seems in Spring 3 they have removed the logic that executes the global interceptors first. Now the interceptors are executed in the order in which they are declared.
Note however that the postHandle of the interceptors is executed in REVERSE order!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With