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,
- 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.
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.
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 ofHandlerInterceptor 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 3 MVC Interceptor Example
In this below example,
- 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
package com.javapapers.spring.mvc.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
@Component
public class AnimalInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("AnimalInterceptor: REQUEST Intercepted for URI: "
+ request.getRequestURI());
request.setAttribute("special", "I Love Animals!");
return true;
}
}
GreetingInterceptor.java
package com.javapapers.spring.mvc.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
@Component
public class GreetingInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("GreetingInterceptor: REQUEST Intercepted for URI: "
+ request.getRequestURI());
request.setAttribute("greeting", "Happy Diwali!");
return true;
}
}
spring-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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-scan base-package="com.javapapers.spring.mvc" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/view/" /> <property name="suffix" value=".jsp" /> <property name="order" value="1" /> </bean> <mvc:interceptors> <bean class="com.javapapers.spring.mvc.interceptor.GreetingInterceptor" /> <mvc:interceptor> <mvc:mapping path="/AnimalList" /> <bean class="com.javapapers.spring.mvc.interceptor.AnimalInterceptor" /> </mvc:interceptor> </mvc:interceptors> </beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns: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
package com.javapapers.spring.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloWorldController {
@RequestMapping("/")
public String hello() {
return "hello";
}
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String hi(@RequestParam("name") String name, Model model) {
String message = "Hi " + name + "!";
model.addAttribute("message", message);
return "hi";
}
}
ZooController.java
package com.javapapers.spring.mvc.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.javapapers.spring.mvc.Animal;
import com.javapapers.spring.mvc.AnimalService;
@Controller
public class ZooController {
protected AnimalService animalService = new AnimalService();
@RequestMapping(value = "/AnimalList", method = RequestMethod.GET)
public String getAnimals(Model model) {
List animalList = animalService.getAnimalList();
model.addAttribute("animalList", animalList);
return "AnimalList";
}
}
view – JSPs
AnimalList.jsp:
<html>
<body>
<em>Welcome! <c:out value="${greeting}"></c:out> <c:out value="${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:out value="${greeting}"></c:out> <c:out value="${special}"></c:out></em>
<hr />
<h1><c:out value="${message}"></c:out></h1>
<h2><a href="./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:out value="${greeting}"></c:out> <c:out value="${special}"></c:out></em>
<hr /><h1>Hello World!</h1><hr />
<h2><a href="./AnimalList">Animal List</a></h2><hr/>
<form action="hi">Name: <input type="text" name="name">
<input type="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.
Output (only GreetingInterceptor):
Output (for page /AnimalList ) both interceptors invoked:
Server Console Log for the Interceptors:
The log statements we have added in the Spring interceptor classes will come in log as follows,
GreetingInterceptor: REQUEST Intercepted for URI: /springmvcinterceptor/
GreetingInterceptor: REQUEST Intercepted for URI: /springmvcinterceptor/AnimalList
AnimalInterceptor: REQUEST Intercepted for URI: /springmvcinterceptor/AnimalList
This Spring tutorial was added on 18/10/2013.
转自http://javapapers.com/spring/spring-mvc-handler-interceptor/