Spring MVC Interceptor with Example

What is Spring MVC Interceptor? In Web application when request comes to the controller , the HandlerMapping handler matches the incoming request. DispatcherServlet will hand it over to the handler mapping, to let it inspect the request and come up with an appropriate HandlerExecutionChain. Then the DispatcherServlet will execute the handler and interceptors in the chain. When it comes to interceptors you can perform the your logic like logging, method tracking etc. Lets see In below Request Flow Diagram of Spring3MVC framework as discuss in the earlier chapter.

 

Spring MVC Interceptor with Example

As diagram we can see that Spring3MVC Interceptor framework intercepts an incoming HTTP request before it reaches your Spring MVC controller class, or conversely, intercepts the outgoing HTTP response after it leaves your controller, but before it’s fed back to the browser.

Why we use Spring3 MVC Interceptor
The answer is that it allows you to perform tasks that are common to every request or set of requests without the need to cut ‘n’ paste boiler plate code into every controller class. For example, you could perform user authentication of a request before it reaches your controller and, if successful, retrieve some additional user details from a database adding them to the HttpServletRequest object before your controller is called. Your controller can then simply retrieve and use these values or leave them for display by the JSP. On the other hand, if the authentication fails, you could re-direct your user to a different page.


Quick Overview of Spring Interceptor:
Each interceptor you define must implement org.springframework.web.servlet.HandlerInterceptor interface. There are three methods that need to be implemented.


1. 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.

2. postHandle(..) —  is called after the handler is executed.

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

These three methods should provide enough flexibility to do all kinds of preprocessing and postprocessing.

package com.dineshonjava.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

/**
 * @author Dinesh Rajput
 *
 */
public class HelloWorldInterceptor implements HandlerInterceptor {

 @Override
 public void afterCompletion(HttpServletRequest request,
   HttpServletResponse response, Object object, Exception exception)
   throws Exception {

 }

 @Override
 public void postHandle(HttpServletRequest request, HttpServletResponse response,
   Object object, ModelAndView modelAndView) throws Exception {

 }

 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
   Object object) throws Exception {
  return false;
 }
}

Once the interceptor is defined, you can ask Spring MVC to configure it via <mvc:interceptors> tag within sdnext-servlet.xml file.

<mvc:interceptors>
  <bean class="com.dineshonjava.interceptor.HelloWorldInterceptor"></bean>
</mvc:interceptors> 

Let us start with the complete application for interceptor. We will create a HelloWorldInterceptor that logs and tracks each coming requests.

In this example show how to write a simple web based Hello World application using Spring 3.0 MVC Interceptor framework. To start with it, let us have working with STS IDE in place and follow the following steps to develop a Dynamic Web Application using Spring 3.0 Web MVC Framework:

Step 1: Create a Dynamic Web Project with a name Spring3MVCInterceptorApp and create two packages com.dineshonjava.controller and com.dineshonjava.interceptor under the src folder in the created project.

Step 2: Add below mentioned Spring 3.0 libraries and other libraries into the folder WebRoot/WEB-INF/lib

/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/commons-fileupload-1.1.1.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/commons-io-1.2.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/commons-logging-1.1.1.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/hibernate-validator-4.0.2.GA.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/jstl-1.2.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/log4j-1.2.14.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/servlet-2.3.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/slf4j-api-1.5.6.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/slf4j-log4j12-1.5.6.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-asm-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-beans-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-context-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-core-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-expression-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-web-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-webmvc-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/validation-api-1.0.0.GA.jar 

Step 3: Create a Java class HelloWorldController under the com.dineshonjava.controller package and another HelloWorldInterceptor under the com.dineshonjava.interceptor package.

Step 4: Create Spring configuration files Web.xml and sdnext-servlet.xml under the WebRoot/WEB-INF/  folder.

Step 5: Create a sub-folder with a name views under the WebRoot/WEB-INF folder. Create a view file hello.jsp under this sub-folder.

Step 6: The final step is to create the content of all the source and configuration files name sdnext-servlet.xml under the sub-folder WebRoot/WEB-INF/config and export the application as explained below.

Software versions used to run the sample code:

  • Spring 3.0
  • Java 1.6
  • Tomcat 7
  • JSTL 1.2
  • STS Java EE IDE

Web Application Structure:

Spring MVC Interceptor

Now we create the HelloWorldController file.

HelloWorldController.java

package com.dineshonjava.controller;

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

/**
 * @author Dinesh Rajput
 *
 */
@Controller
@RequestMapping("/hello")
public class HelloWorldController {
 
 @RequestMapping(method = RequestMethod.GET)
 public String sayHelloWorld(ModelMap model) {
  model.addAttribute("message", "Spring 3.0 MVC Framework Hello World Example with Interceptor!");
  model.addAttribute("auther", "DineshOnJava");
  return "hello";
 }
}

The controller has one method sayHelloWorld() which is mapped to URL /hello using @RequestMapping. This simply paints the hello.jsp view.

hello.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<html>
 <head>
    <title>Spring 3.0 MVC Hello World Example</title>
 </head>
 <body>
 <h2>
${message} </h2>
 <h2>
${auther} </h2>
</body>
</html>


Following is the content of Spring Web configuration file web.xml

<web-app id="WebApp_ID" version="3.0" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <display-name>SpringMVCHelloWorld</display-name>
  <welcome-file-list>
 <welcome-file>/</welcome-file>
  </welcome-file-list>
 
    <servlet>
        <servlet-name>sdnext</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
      <init-param>
            <param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/sdnext-servlet.xml</param-value></init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>sdnext</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>


Following is the content of another Spring Web configuration file sdnext-servlet.xml

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="
 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
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven></mvc:annotation-driven>

<context:component-scan base-package="com.dineshonjava.controller">
</context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
 <property name="prefix" value="/WEB-INF/views/"></property>
 <property name="suffix" value=".jsp"></property>
</bean>

<mvc:interceptors>
     <bean class="com.dineshonjava.interceptor.HelloWorldInterceptor"></bean>
</mvc:interceptors> 
 
</beans>

Once you are done with creating source and configuration files, export your application. Right click on your application and use Export -> WAR File option and save your Spring3MVCInterceptorApp.war file in Tomcat’s web apps folder.

Now start your Tomcat server and make sure you are able to access other web pages from web apps folder using a standard browser. Now try to access the URL http://localhost:8080/sdnext/hello and if everything is fine with your Spring Web Application, you should see the following result:

 

Spring MVC Interceptor with Example

Download Source Code+Libs
Spring3MVCInterceptorApp.zip 

 

<<Spring Web MVC Framework |index| Spring 3 MVC Internationalization & Localization with Example>>  

Previous
Next

7 Comments

  1. Mario Guerrero January 2, 2013
  2. Dinesh Rajput January 2, 2013
  3. Anonymous January 5, 2013
  4. Majid August 30, 2013
  5. Dinesh August 31, 2013
  6. loke November 15, 2013
  7. Dinesh November 18, 2013