Handler Interceptors
Spring MVC gives you option to do something or rather give you a handle by which to control the action before the controller is called, after it is called and after completion of flowing of control from the view to the DispatcherServlet in the form of Handler Interceptors.
It can be considered as very much similar to AOP but more to do with Spring MVC controllers. Listing 14-12 below shows the definition of HandlerInterceptor interface.
Listing 14-12. HandlerInterceptor interface definition
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.springframework.web.servlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public interface HandlerInterceptor { boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception; void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception; void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception; } |
Figure 14-10 below shows calling of HandlerInterceptor methods at various stages in a typical Spring MVC request flow.
Figure 14-10. HandlerInterceptor method invocation in Spring MVC request flow
Before going into the configuration details of HandlerInterceptor, below summarized are some of the uses of this:
- Can do functionalities which are considered common to many controllers
- Auditing requests or as a matter of fact anything considered important
- Setting of response headers if necessary
- Measuring performance and logging in performance quantitatively
- Adding common attributes to models
While declaring your HandlerMapping, you can define your HandlerInterceptor as shown in Listing 14-13 below.
Listing 14-13. Declaring HandlerInterceptor while declaring HandlerMapping
1 2 3 4 5 6 7 8 9 10 11 |
<beans …> <bean class="org.springframework.web.servlet.mvc.annotation. DefaultAnnotationHandlerMapping"> <property name="interceptors"> <list> <bean class="…SampleAuditInterceptor"/> <bean class="…SamplePerformanceInterceptor"/> </list> </property> </bean> </beans> |
Spring 3.0 introduces some very good configuration simplifications to configuring HandlerInterceptors as shown in Listing 14-14 below in which these interceotrs will be applied to all HandlerMapping.
Listing 14-14. Simplification of HandlerInterceptor configuration – Applies to all HandlerMapping
1 2 3 4 5 6 |
<beans …> <mvc:interceptors> <bean class="…SampleAuditInterceptor"/> <bean class="…SamplePerformanceInterceptor"/> </mvc:interceptors> </beans> |
Page Visitors: 7592


Tomcy John


Latest posts by Tomcy John (see all)
- A Guide to Continuous Improvement for Architects - February 2, 2023
- Cloud-first Architecture Strategy - January 26, 2023
- Architecture Strategy and how to create One - January 24, 2023