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 {

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


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


 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.

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

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


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.


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


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

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

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">


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="

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

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

<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 class="com.dineshonjava.interceptor.HelloWorldInterceptor"></bean>

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

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


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