Spring 3 MVC Interceptor tutorial with example

Spring MVC provides a powerful mechanism to intercept an http request. Similar to Servlet Filter concept, Spring MVC provides a way to define special classes called Interceptors that gets called before and after a request is served.

Quick Overview

Each interceptor you define must implement org.springframework.web.servlet.HandlerInterceptor interface. There are three methods that need to be implemented.

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.

postHandle(..) is called after the handler is executed;

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

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

You can define an interceptor class as follow:

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

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

public class HelloWorldInterceptor implements HandlerInterceptor  {
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		System.out.println("Pre-handle");
		
		return true;
	}
	//override postHandle() and afterCompletion() 
}

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

	<mvc:interceptors>
      <bean class="net.viralpatel.spring3.interceptor.HelloWorldInterceptor" />
	</mvc:interceptors> 

Let us start with the complete Demo application. We will create a demo Interceptor that logs each request.

Tools and technologies:

  1. Java 5 (or above)
  2. Spring MVC 3.0 (or above)
  3. Eclipse 3.2 (or above)

We will need following JAR files in order to execute this project.
spring-interceptor-jar-files

If you are using Apache Maven as dependency management, add following dependencies to pom.xml.

  <dependencies>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-webmvc</artifactId>
    	<version>3.0.1.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>jstl</groupId>
    	<artifactId>jstl</artifactId>
    	<version>1.2</version>
    </dependency>
  </dependencies>

Let us create a simple Spring MVC Interceptor class that logs each request.

Step 1: The Controller – Create new Spring MVC Controller

We create a simple Spring MVC controller that displays a plain JSP view.

HelloWorldController.java

package net.viralpatel.spring3.controller;

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

@Controller
public class HelloWorldController {

	
	@RequestMapping(value = "/hello", method = RequestMethod.GET)
	public String sayHello() {
		return "hello";
	}
}

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

Step 2: The View – Create new JSPs

Create two JSPs, hello.jsp that displays hello message and index.jsp that simply redirects first request to /hello.html.

/WEB-INF/jsp/hello.jsp

<html>
<head>
	<title>Spring MVC Interceptor example</title>
</head>
<body>
	<h1>Hello!!</h1>
</body>
</html>

WebContent/index.jsp

<jsp:forward page="hello.html"></jsp:forward>

The index.jsp simply redirects to hello.html which calls the HelloWorldController.

Step 3: The Interceptor – Spring MVC HandlerInterceptor

Let’s create the Spring based Handler Interceptor which will intercept the request and print a message.

HelloWorldInterceptor.java

package net.viralpatel.spring3.interceptor;

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

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

public class HelloWorldInterceptor implements HandlerInterceptor  {
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		System.out.println("Pre-handle");
		
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("Post-handle");
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("After completion handle");
	}
}

Thus in each of the method preHandle, postHandle and afterCompletion we print a message on console.

Step 4: Spring Configuration

Now lets glue up the source code and configure Spring. Note how we declared the interceptor in spring-servlet.xml using <mvc:interceptors> tag.

spring-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
		
	<context:annotation-config />
	<context:component-scan base-package="net.viralpatel.spring3.controller"/>
	
	<mvc:interceptors>
      <bean class="net.viralpatel.spring3.interceptor.HelloWorldInterceptor" />
	</mvc:interceptors> 
	
  <bean id="jspViewResolver"
	class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
  </bean>
</beans>

Also configure the spring’s DispatcherServlet in web.xml file.

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>Spring3MVC-Interceptor example</display-name>
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>
</web-app>

Final Project Structure

Once all the source files and configuration files are in place, your project should look like below:

spring-mvc-handle-interceptors-project

Demo

Compile and execute the project in Eclipse. Open below URL in browser.

URL: http://localhost:8080/SpringMVC_Interceptor_example/
spring-interceptor-example-demo

Check the server console logs. You must see following:

Pre-handle
Post-handle
After completion handle

Download Source Code

SpringMVC_Multi_Interceptor_example.zip (2.5 MB)



32 Comments

  • Pallavi 22 November, 2012, 11:36

    Nice Tutorial.

  • sagar 3 December, 2012, 18:39

    i love you viral without you m nothing in this industry ……….. ;)

  • praveen 4 January, 2013, 4:18

    Download source code downloading some other project source code. Please advise

  • praveen 4 January, 2013, 4:25

    I added following dependencies but getting compilation error with these two imports in controller class

    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>3.0.1.RELEASE</version>
      </dependency>
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    
  • Rajesh 25 January, 2013, 6:39

    Viral, Java 6 will be required for Annotations that you have used like @Override..

  • Trent Payne 28 January, 2013, 10:05

    Thanks!

    This description solved my problem nicely!!

  • Viral 5 March, 2013, 11:39

    I want to develop a complte web applicationn in spring frame work where I can connect to oracle DB and I have front end and data validation done

    Please help me

  • eugene 9 March, 2013, 4:30

    I encounterd error blow. why??? Please help me ^^;;

    Caused By: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘mvc:interceptors’.

    ——————————
    xmlns:mvc=”http://www.springframework.org/schema/mvc”

    • rajimoonp 28 May, 2013, 16:51

      @eugene
      add xmlns:mvc=”http://www.springframework.org/schema/mvc” @ header

  • donghai.wan 27 March, 2013, 15:35

    Thanks very much

  • ggk@hotmail.com 8 April, 2013, 6:27

    Thank you very much!!!

  • naveen 25 April, 2013, 6:19

    thank you so much for your post, a sensible example which i’ve seen after searching about 50 sites… cheers :)

  • Ravi 18 May, 2013, 10:50

    Can anyone help me how to configure maven in eclipse?

  • kuldip soni 10 July, 2013, 17:32

    Hi Viral,

    My functionality is when i click on link of my application page, it will open xml in another window.

    i want to hide or change url of that window, how can i achive using above interceptor ?

    Please help

    Thanks

  • Mounika 5 September, 2013, 19:50

    Can you please tell me the real time applications where we will use interceptors most..? What is use of pre handling, or post handling the requests. Please Explain me with any real time scenarios. Thanks in advance.

    • Michael C. 7 September, 2013, 4:38

      I can tell you what I use a HandlerInterceptor for. In my application, which is an e-commerce engine, I use a HandlerInterceptor to resolve certain things that all controllers will need to have at their disposal before they can render a response. I initialize certain things like the particular store they’re accessing, the user’s shopping cart, navigation UI, robots rules, client timezone, etc. If I didn’t do those things inside an interceptor, then I would have to do repeat all of those initializations inside of each controller method, which would make my code a lot more redundant and less readable. Whatever you find yourself repeating a lot in controller methods can be factored out and handled inside an interceptor. I hope that gives you some more insight.

    • raju 29 November, 2013, 19:57

      Hi,

      These ‘interceptors’ are useful to validate requests from client.
      For Eg:
      It is useful to avoid spam requests By Validating the request according to Your app Requirements(You allow the request to Process Furthur only it has perticuls credentials).
      And you can Provide Secirity by Restricting the invalid requests to access the resources of your App.

      Thanks & Regards
      raju.

    • krishna 4 July, 2014, 21:49

      we will interceptors used for setMaxAgeForSession, checkIfRequestIsAllowedWithoutLogIn some other purposes…

  • Michael C. 7 September, 2013, 4:33

    Do you know of a way to intercept requests BEFORE a handler has been chosen? The reason I want to know is because some parts of my application have dynamic URLs (neither in XML nor in @RequestMapping annotations) that are stored in a database and updated via a web front-end. As such, static URL-to-controller mappings won’t work in my case (think of an app like a CMS where end users can choose their own URL for a particular page). Any ideas?

  • Joseph 25 September, 2013, 20:21

    Great tutorial! Really simple and easy to follow. Thanks!! Using this to put a CorsFilter in.

  • srinu 18 November, 2013, 12:47

    i have an error above code:

    HTTP Status 500 – An exception occurred processing JSP page /index.jsp at line 1
    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

    • isssss 19 November, 2013, 16:02

      write ur jsp code here,error in line1 of ur jsp, you hv written smthig that is nt accepted

  • srinu 18 November, 2013, 12:48

    any one is help 2 me above http status…

  • Mahendra 4 December, 2013, 9:37

    Any tell me how to close a session when browser tab closeed i am usin Spring ,Jsf 1.8 Icefaces

  • naresh 8 January, 2014, 0:02

    hi patel

    Great tutorial! Really simple and easy to follow. Thanks!!
    i need gosu technology sample project with source code
    please send me viralpatel very urjent …..

  • Green 25 March, 2014, 16:14

    What if I want to inject interceptor logic for a certain method on a certain controller? Is there an easy to to achieve that? Literally I am looking for something like @Before or @After annotation in PlayFramework (see http://www.playframework.com/documentation/1.2/controllers#interceptions) in spring

  • Knight 15 April, 2014, 14:57

    Hi,

    Really nice tutorial. I understood the whole concept. I only dont understand where have we linked the interceptor to handler. I mean how does the framework know that the HelloWorldInterceptor is to be called for request to HelloWorldController controller

  • Seetesh 11 July, 2014, 14:22

    This example doesnt work on JBoss 7.1.1

  • Seetesh 11 July, 2014, 14:58

    Example doesnt work on Jboss.

    This line gives error

    xmlns:mvc=”http://www.springframework.org/schema/mvc”

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *