All HandlerMapping
implementations support handler interceptors, which are useful if you need to apply specific functionality to specific requests - for example, checking for the presence of a main request. Interceptors must implement HandlerInterceptor
from the org.springframework.web.servlet
package with three methods that should provide enough flexibility to perform all kinds of pre- and post-processing:
-
preHandle(..)
: Before the actual handler is executed -
postHandle(..)
: After the handler is executed -
afterCompletion(..)
: After the request is completed
The preHandle(..)
method returns a Boolean value. This method can be used to interrupt or continue processing of the execution chain. If this method returns true
, the handler execution chain continues. If it returns false, DispatcherServlet
assumes that the interceptor itself has processed the requests (and, for example, rendered the corresponding view), and does not continue executing other interceptors and the actual handler in the execution chain.
You can also register them directly using setters in separate HandlerMapping
implementations.
The postHandle
method is less useful when using methods marked with the @ResponseBody
annotation and ResponseEntity
methods for which the message is written and captured within the HandlerAdapter
and before postHandle
. This means that it will be too late to make any changes to the message, such as adding an extra header. For such scenarios, you can implement ResponseBodyAdvice
and either declare it as an Advice controller bean, or configure it directly for RequestMappingHandlerAdapter
.
GO TO FULL VERSION