SpringMVC - 4. Spring MVC Handler Interceptor

Spring MVC Handler Interceptor

Spring MVC’s handler interceptor is like a good friend and will help in time of need. Spring’s handler interceptor as rightly named, intercepts a request, html

  • just before the controller or
  • just after the controller or
  • just before the response sent to view

Spring’s interceptor can be configured for all the requests (for any URI’s requested) or for a group of URI’s (may be for a set of modules, etc.). Just remember controller and handler are the same. If you are a beginner in Spring, to better understand interceptor, please go through the Spring 3 MVC tutorial. java

In real scenario, Spring MVC handler interceptors are used for authentication, logging, to add a common message to all response. For the pages displayed we want to remove all bold tags from the response, it is possible using Spring interceptor. web

Important Points about Spring Interceptor

  • HandlerInterceptor – an interface, which must be implemented by the Spring interceptor classes, has the following three methods.
  • preHandle(…) – called just before the controller
  • postHandle(…) – called immediately after the controller
  • afterCompletion(…) – called just before sending response to view
  • HandlerInterceptorAdaptor – an implementation class of HandlerInterceptor interface provided by Spring as a convenient class. By extending this we can override only the necessary methods out of the three.
  • Interceptor classes must be declared in spring context xml configuration file within the tag <mvc:interceptors>
  • Interceptor can be configured to execute in two ways, execute for all requests and map to specific url requests.
  • ORDER: All global interceptors gets executed first and then the mapped interceptor. Among them, the same order in which the interceptor are declared, the execution is also done.
  • If true is returned, the execution chain continues and for false, the execution stops for that request with that interceptor.

Note: My opinion on the interceptor spring configuration is, it still follows the old XML based configuration type. It will be better if the annotation based configuration is also brought into this interceptor declaration as we are doing for the controllers. spring

Spring 3 MVC Interceptor Example

In this below example, express

  • Used two controllers helloworldcontroler and zoocontroller.
  • HelloWorldConroller will get input from user and display the same in next page. ZooController, lists out a set of animals in a screen.
  • Two interceptors declared. GreetingInterceptor is configured to be called for all the request. AnimalInterceptor is configured to be called only for the page /AnimalList (in path mapping we can use spring expression to choose a set of pages also).
  • GreetingInterceptor and AnimalInterceptor respectively add a value to request attribute ‘greeting’ and ‘special’.
  • In all the jsp pages both the attribute are displayed. But from the output you can see, only in /AnimalList page both values are displayed and in all other pages only the ‘greeting’ value is displayed. 

AnimalInterceptor.java


packagecom.javapapers.spring.mvc.interceptor;
  
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
  
importorg.springframework.stereotype.Component;
importorg.springframework.web.servlet.handler.HandlerInterceptorAdapter;
  
@Component
publicclassAnimalInterceptorextendsHandlerInterceptorAdapter {
  publicbooleanpreHandle(HttpServletRequest request,
      HttpServletResponse response, Object handler)throwsException {
    System.out.println("AnimalInterceptor: REQUEST Intercepted for URI: "
        + request.getRequestURI());
    request.setAttribute("special","I Love Animals!");
    returntrue;
  }
}


GreetingInterceptor.java


packagecom.javapapers.spring.mvc.interceptor;
  
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
  
importorg.springframework.stereotype.Component;
importorg.springframework.web.servlet.handler.HandlerInterceptorAdapter;
  
@Component
publicclassGreetingInterceptorextendsHandlerInterceptorAdapter {
  publicbooleanpreHandle(HttpServletRequest request,
      HttpServletResponse response, Object handler)throwsException {
    System.out.println("GreetingInterceptor: REQUEST Intercepted for URI: "
        + request.getRequestURI());
    request.setAttribute("greeting","Happy Diwali!");
    returntrue;
  }
}

spring-context.xml


<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
  <context:annotation-config/>
  <context:component-scanbase-package="com.javapapers.spring.mvc"/>
  
  <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <propertyname="prefix"value="/view/"/>
    <propertyname="suffix"value=".jsp"/>
    <propertyname="order"value="1"/>
  </bean>
  
  <mvc:interceptors>
    <beanclass="com.javapapers.spring.mvc.interceptor.GreetingInterceptor"/>
    <mvc:interceptor>
      <mvc:mappingpath="/AnimalList"/>
      <beanclass="com.javapapers.spring.mvc.interceptor.AnimalInterceptor"/>
    </mvc:interceptor>
  </mvc:interceptors>
  
  
</beans>

web.xml


<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID"version="2.5">
  
  <display-name>Spring MVC Excel Export</display-name>  
    
  <servlet>
        <servlet-name>springMVCDispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
      <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/spring-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVCDispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  
    
</web-app>

HelloWorldController.java


packagecom.javapapers.spring.mvc.controller;
  
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.Model;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.bind.annotation.RequestParam;
  
@Controller
publicclassHelloWorldController {
  
  @RequestMapping("/")
  publicString hello() {
    return"hello";
  }
  
  @RequestMapping(value ="/hi", method = RequestMethod.GET)
  publicString hi(@RequestParam("name") String name, Model model) {
    String message ="Hi "+ name +"!";
    model.addAttribute("message", message);
    return"hi";
  }
  
}

ZooController.java


packagecom.javapapers.spring.mvc.controller;
  
importjava.util.List;
  
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.Model;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
  
importcom.javapapers.spring.mvc.Animal;
importcom.javapapers.spring.mvc.AnimalService;
  
@Controller
publicclassZooController {
  
  protectedAnimalService animalService =newAnimalService();
  
  @RequestMapping(value ="/AnimalList", method = RequestMethod.GET)
  publicString getAnimals(Model model) {
    List<Animal> animalList = animalService.getAnimalList();
    model.addAttribute("animalList", animalList);
    return"AnimalList";
  }
  
}

view – JSPs


AnimalList.jsp:
<html>
<body>
<em>Welcome! <c:outvalue="${greeting}"></c:out> <c:outvalue="${special}"></c:out></em>
<hr/>
<h1>Example for Spring MVC Excel Export</h1>
<h2>Animal List</h2>
...
  
  
hi.jsp:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html><head><title>Result</title></head><body>
<em>Welcome! <c:outvalue="${greeting}"></c:out> <c:outvalue="${special}"></c:out></em>
<hr/>
        <h1><c:outvalue="${message}"></c:out></h1>        
        <h2><ahref="./AnimalList">Animal List</a></h2>
    </body></html>
  
hello.jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html><head><title>Home</title></head><body>
<em>Welcome! <c:outvalue="${greeting}"></c:out> <c:outvalue="${special}"></c:out></em>
<hr/><h1>Hello World!</h1><hr/>
<h2><ahref="./AnimalList">Animal List</a></h2><hr/>
<formaction="hi">Name: <inputtype="text"name="name"> 
<inputtype="submit"value="Submit"></form>
</body></html>

Other Classes

Animal.java and AnimalService.java are of not much interest to the Spring MVC interceptor topic, but required to run the example and included in the download below. api

Output (only GreetingInterceptor):

Interceptor 1

Output (for page /AnimalList ) both interceptors invoked:

Intercept or 2

Server Console Log for the Interceptors:

The log statements we have added in the Spring interceptor classes will come in log as follows, spring-mvc

GreetingInterceptor: REQUEST Intercepted for URI: /springmvcinterceptor/
GreetingInterceptor: REQUEST Intercepted for URI: /springmvcinterceptor/AnimalList
AnimalInterceptor: REQUEST Intercepted for URI: /springmvcinterceptor/AnimalList
session

相關文章
相關標籤/搜索