Expert Spring MVC and Web Flow

(Dana P.) #1

Listing 6-78.HandlerInterceptor Interface


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;
}


Three life cycle points can be intercepted. See Table 6-4.

Table 6-4.Interceptor Life Cycle Points


Method Name Description


preHandle Called before the request handler is invoked. If it returns false, the request
handler is never invoked, and the rest of the interceptor’s methods are never
called.


postHandle Called after the handler finishes but before the view is rendered. Useful for
placing common objects into the model.


afterCompletion Called after the view is rendered, even if there was an error in handling the
request. Useful for resource cleanup.


HandlerInterceptor Example


Our simple example of a HandlerInterceptor(shown in Listing 6-79) will insert the current
time into the model after the controller has finished, but before the view is rendered. The diffi-
cult part of using interceptors is not in implementing them but in configuring them.


Listing 6-79.HandlerInterceptor Example


public class DateInsertionInterceptor implements HandlerInterceptor {


public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
return true; // always continue
}

public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
modelAndView.addObject("currentTime", new Date());
}

CHAPTER 6 ■THE CONTROLLER MENAGERIE 197
Free download pdf