Thursday, December 15, 2016

Spring Interceptors

Interceptors are for intercepting the controller methods. These are called before the control is passed to the controller method. You can intercept HTTP request and perform some actions on it and then hand over it to controller methods.You have to configure the interceptors in the project-servlet.xml.

Spring Interceptors can be used anywhere because it is defined in the Application context.

Spring interceptors can be used for security stuff in your business layer or logging or bug tracking that is independent of the web layer.


spring interceptor


Spring Interceptor – HandlerInterceptor


Three methods to implement spring interceptor

boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler): used to intercept the request before it goes to handler method. This method returns the boolean value.

If true is returned, then request is processed through another spring interceptor or to send it to handler method if there are no further spring interceptors.

If false is returned, then there is no further processing of this request. Use response object to send response to the client request in this case.
Object handler is object to handle the request. Spring MVC Exception Handling can be used to handle exceptions if thrown and useful to send error page as response.

void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView): method can be used to calculate the time taken by handler method to process the request. postHandle() as name suggests is called when HandlerAdapter has called the handler but Dispatcher Servlet still has to render the view.

ModelAndView object is injected to add additional attributes that can be used in the view page.

void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex): as the name says this method is called after the view is rendered.

Interceptor Example:


Calculate the execution time and save it into the ModelAndView object to display it on the page.


Spring Interceptor – Controller Class


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
publicclassHomeController{
      @RequestMapping(value ="/home", method =RequestMethod.GET)
      publicString home(Model model){
            return"home";
      }
}

Spring Interceptor - HandlerInterceptorAdapter


package com.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
public class RequestProcessingTimeInterceptor extends 
  HandlerInterceptorAdapter {
   @Override
   public boolean preHandle(HttpServletRequest request,
    HttpServletResponse response,Object handlerthrows Exception {
      long startTime = System.currentTimeMillis();
      System.out.println("Request URL ::" + request.getRequestURL()
          + " :: Start Time :: " + startTime);
      request.setAttribute("startTime", startTime);
      return true;
   }
   @Override
   public void preHandle(HttpServletRequest request, 
    HttpServletResponse response,Object handlerthrows Exception {
       
      long startTime = (long) request.getAttribute("startTime");
      System.out.println("Request URL :: " + 
         request.getRequestURL().toString() + " :: End time :: "
         + System.currentTimeMillis());
      System.out.println("Request URL :: " + 
         request.getRequestURL().toString() + " :: Time Taken :: "
         + (System.currentTimeMillis() - startTime));
      }
}

Spring Interceptor : dispatcher-servlet.xml Configuration


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:beans="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/mvc 
   http://www.springframework.org/schema/mvc/spring-mvc.xsd
   http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context.xsd">
  <annotation-driven/>
  <beans:bean
     class="org.springframework.web.servlet.view.
                                    InternalResourceViewResolver">
     <beans:propertyname="prefix"value="/WEB-INF/views/"/>
     <beans:propertyname="suffix"value=".jsp"/>
  </beans:bean>
  <!-- Configuring interceptors based on URI -->
  <interceptors>
     <interceptor>
     <mapping path="/*"/>
     <beans:bean 
         class="com.web.controller.RequestProcessingTimeInterceptor">
     </beans:bean>
  </interceptor>
</beans:beans>



No comments:

Post a Comment