Spring MVC

Interceptors in MVC

(reference : http://www.journaldev.com/2676/spring-mvc-interceptors-example-handlerinterceptor-and-handlerinterceptoradapter)

Sometimes  we want to intercept a request , do some processing/validation etc before handling it to controller method. Lets say, for a particular page request we want to check whether user is logged in or not. We can do that using an interceptor.


How do we implement  an interceptor?

1. We will need to write an interceptor class by implementing interface HandlerInterceptor or extending its abstract implemented class HandlerInterceptorAdapter.
override one of the three interceptor methods as per your need. 

 * boolean  preHandle(HttpServletRequest request, HttpServletResponse response, Object                                                   handler)


  this interceptor method will be called  after HandlerMapping determined an appropriate handler object, but before HandlerAdapter invokes the handler.

 you need to return true if you want to proceed with the next interceptor from interceptor chains or 
handler.
return false if you do not want to proceed further in processing the request.

* void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,                                        ModelAndView modelAndView) throws Exception;


Called after HandlerAdapter actually invoked the handler, but before the DispatcherServlet renders the view.Can expose additional model objects to the view via the given ModelAndView.


* void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object                           handler, Exception ex) throws Exception;

This method if implemented gets called after handler has rendered a view.Will be called on any outcome of handler execution, thus allows  for proper resource cleanup.


If there are multiple interceptors configured, preHandle() method is executed in the order of configuration whereas postHandle() and afterCompletion() methods are invoked in the reverse order.




No comments:

Post a Comment