Thursday, 28 January 2016

Spring MVC interceptor

Each interceptor you define must implementorg.springframework.web.servlet.HandlerInterceptor interface. There are three methods that need to be implemented.
preHandle(..) is called before the actual handler is executed;
The preHandle(..) method returns a boolean value. You can use this method to break or continue the processing of the execution chain. When this method returns true, the handler execution chain will continue; when it returns false, the DispatcherServlet assumes the interceptor itself has taken care of requests (and, for example, rendered an appropriate view) and does not continue executing the other interceptors and the actual handler in the execution chain.
postHandle(..) is called after the handler is executed;

afterCompletion(..) is called after the complete request has finished.


How to implement?
1    1.   Spring MVC to configure it via <mvc:interceptors>tag within spring-servlet.xml file.
<mvc:interceptors>
  <bean class="raj.interceptor.HelloWorldInterceptor" />
</mvc:interceptors>


 2.            The Interceptor – Spring MVC HandlerInterceptor
   package raj.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

   import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class HelloWorldInterceptor implements HandlerInterceptor  {

//overriding abstract method (mandatory)

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
         
      System.out.println("Pre-handle");
         
        return true;
    }

//overriding abstract method (mandatory)
     
   @Override
    public void postHandle(HttpServletRequest request,
           HttpServletResponse response, Object handler,
           ModelAndView modelAndView) throws Exception {
       System.out.println("Post-handle");
   }
     //overriding abstract method (mandatory)
   @Override
   public void afterCompletion(HttpServletRequest request,
           HttpServletResponse response, Object handler, Exception ex)
           throws Exception {
       System.out.println("After completion handle");
   }
}



3. use your filter logic in prehandle method of abovesaid class !! 

its done..!!

No comments:

Post a Comment