Spring MVC Intercepting Request using HandlerInterceptor

In any web application, sometimes we need to intercept the http request before we process the request.
And sometimes we need to perform something immediately after the request is completed its processing.

All this can be achieved by using Interceptors in Spring.

All the interceptors in spring mvc must implement the interface org.springframework.web.servlet.HandlerInterceptor
Or
All interceptors must extend the abstract class
org.springframework.web.servlet.handler.HandlerInterceptorAdapter

and override the below required methods

1)public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
This method handles the request before it is passed to the controller.
If it returns true , spring will continue the request processing with another interceptor if any and if no other interceptors exist, it will pass the request to the Controller.

If it returns false, Spring will assume that request is handled by the interceptor itself and it will not pass the request to controller or any other interceptors.

2)public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)

This method is called after the request processing is done from controller and before the Disptcher servlet renders the view.
This is useful if we need to add any additional attribute to the modelmap.

3)public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
This method is called when the request processing is complete and after the view is rendered.

The interceptor can be defined as below

  1. public class HelloWorldInterceptor implements HandlerInterceptor {
  2.  
  3.    
  4.     public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
  5.         System.out.println("pre-handle");
  6.         return true;
  7.     }
  8.  
  9. //need to override other 2 methods
  10. }
public class HelloWorldInterceptor implements HandlerInterceptor {

	
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
		System.out.println("pre-handle");
		return true;
	}

//need to override other 2 methods
}

We need to provide the implementation of all 3 methods in our interceptor.

If we want only 1 or 2 methods to override then, make our interceptor class to extend the abstract class HandlerInterceptorAdopter class as explained above

  1. public class HelloWorldInterceptor extends HandlerInterceptorAdopter {
  2.  
  3.    
  4.     public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
  5.         System.out.println("pre-handle");
  6.         return true;
  7.     }
  8.  
  9. //not required to override other 2 methods
  10. }
public class HelloWorldInterceptor extends HandlerInterceptorAdopter {

	
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
		System.out.println("pre-handle");
		return true;
	}

//not required to override other 2 methods
}

After defining it, we need to configure it in the spring configuration file as below

  1. <mvc:interceptors>
  2.       <bean class="com.kb.interceptors.HelloWorldInterceptor" />
  3. </mvc:interceptors>
<mvc:interceptors>
      <bean class="com.kb.interceptors.HelloWorldInterceptor" />
</mvc:interceptors>

Now lets develop our sample application

HelloWorldInterceptor.java

  1. package com.kb.interceptors;
  2.  
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5.  
  6. import org.springframework.web.servlet.HandlerInterceptor;
  7. import org.springframework.web.servlet.ModelAndView;
  8.  
  9. public class HelloWorldInterceptor implements HandlerInterceptor {
  10.  
  11.    
  12.     public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
  13.         System.out.println("pre-handle");
  14.         return true;
  15.     }
  16.    
  17.    
  18.     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView)
  19.             throws Exception {
  20.         System.out.println("post-handle");
  21.        
  22.     }
  23.    
  24.     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception exception)
  25.             throws Exception {
  26.         System.out.println("after-completion");
  27.        
  28.     }
  29.  
  30. }
package com.kb.interceptors;

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 {

	
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
		System.out.println("pre-handle");
		return true;
	}
	
	
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView)
			throws Exception {
		System.out.println("post-handle");
		
	}
	
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception exception)
			throws Exception {
		System.out.println("after-completion");
		
	}

}

Create the Hello World Controller class

HelloWorldController.java

  1. package com.kb.controllers;
  2.  
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5.  
  6. @Controller
  7. public class HelloWorldController {
  8.    
  9.     @RequestMapping("/hello")
  10.     public String hello(){
  11. System.out.println("inside controller");
  12.         return "hello";
  13.     }
  14.    
  15.    
  16.  
  17. }
package com.kb.controllers;

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

@Controller
public class HelloWorldController {
	
	@RequestMapping("/hello")
	public String hello(){
System.out.println("inside controller");
		return "hello";
	}
	
	

}

Create the hello.jsp

hello.jsp

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  4. <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  9. <title>Hello</title>
  10. </head>
  11. <body>
  12.  <div align="center">
  13.         <h2>Hi Welcome</h2>
  14.   </div>
  15. </body>
  16. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello</title>
</head>
<body>
 <div align="center">
        <h2>Hi Welcome</h2>
  </div>
</body>
</html>

Create the spring configuration file

spring-mvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb.*" />
  14.     <mvc:annotation-driven />
  15.  
  16.     <bean id="viewResolver"
  17.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  18.         <property name="prefix" value="/WEB-INF/pages/" />
  19.         <property name="suffix" value=".jsp" />
  20.     </bean>
  21. <mvc:interceptors>
  22.       <bean class="com.kb.interceptors.HelloWorldInterceptor" />
  23. </mvc:interceptors>
  24.  
  25.  
  26. </beans>
<?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:p="http://www.springframework.org/schema/p"
	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-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

	<context:component-scan base-package="com.kb.*" />
	<mvc:annotation-driven />

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>
<mvc:interceptors>
      <bean class="com.kb.interceptors.HelloWorldInterceptor" />
</mvc:interceptors> 


</beans>

Create the web.xml

web.xml

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.     <display-name>Spring Interceptors</display-name>
  6.  
  7.     <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml,
  15.         </param-value>
  16.         </init-param>
  17.         <load-on-startup>1</load-on-startup>
  18.     </servlet>
  19.     <servlet-mapping>
  20.         <servlet-name>mvc-dispatcher</servlet-name>
  21.         <url-pattern>/</url-pattern>
  22.     </servlet-mapping>
  23.  
  24.     <listener>
  25.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  26.     </listener>
  27.  
  28. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Spring Interceptors</display-name>

	<!-- Spring MVC dispatcher servlet -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			/WEB-INF/spring-mvc.xml,
		</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

</web-app>

Create the pom.xml

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>Spring</groupId>
  5.   <artifactId>SpringInterceptors</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>SpringInterceptors Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.    <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.   <dependencies>
  14.     <dependency>
  15.       <groupId>junit</groupId>
  16.       <artifactId>junit</artifactId>
  17.       <version>3.8.1</version>
  18.       <scope>test</scope>
  19.     </dependency>
  20.     <dependency>
  21.             <groupId>org.springframework</groupId>
  22.             <artifactId>spring-web</artifactId>
  23.             <version>${org.springframework.version}</version>
  24.         </dependency>
  25.  
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring-webmvc</artifactId>
  29.             <version>${org.springframework.version}</version>
  30.         </dependency>
  31.         <dependency>
  32.             <groupId>javax.servlet</groupId>
  33.             <artifactId>servlet-api</artifactId>
  34.             <version>2.5</version>
  35.             <scope>provided</scope>
  36.         </dependency>
  37.         <dependency>
  38.     <groupId>javax.servlet.jsp.jstl</groupId>
  39.     <artifactId>javax.servlet.jsp.jstl-api</artifactId>
  40.     <version>1.2.1</version>
  41. </dependency>
  42. <dependency>
  43.     <groupId>taglibs</groupId>
  44.     <artifactId>standard</artifactId>
  45.     <version>1.1.2</version>
  46. </dependency>
  47.   </dependencies>
  48.   <build>
  49.     <finalName>SpringInterceptors</finalName>
  50.     <plugins>
  51.             <plugin>
  52.                 <groupId>org.apache.maven.plugins</groupId>
  53.                 <artifactId>maven-compiler-plugin</artifactId>
  54.                 <version>2.5.1</version>
  55.                 <configuration>
  56.                     <source>1.8</source>
  57.                     <target>1.8</target>
  58.                 </configuration>
  59.             </plugin>
  60.         </plugins>
  61.   </build>
  62. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Spring</groupId>
  <artifactId>SpringInterceptors</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringInterceptors Maven Webapp</name>
  <url>http://maven.apache.org</url>
   <properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
	<groupId>javax.servlet.jsp.jstl</groupId>
	<artifactId>javax.servlet.jsp.jstl-api</artifactId>
	<version>1.2.1</version>
</dependency>
<dependency>
	<groupId>taglibs</groupId>
	<artifactId>standard</artifactId>
	<version>1.1.2</version>
</dependency>
  </dependencies>
  <build>
    <finalName>SpringInterceptors</finalName>
    <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
  </build>
</project>

Now deploy the application and access the below url

http://localhost:8080/SpringInterceptors/hello

Check the output in the console

Check the last few lines which are displaying the output and observe its order.

First line is coming from preHandle() method of our interceptor
Second line is coming from our HelloWorld Controller
Third line is coming from postHandle() method of our interceptor
Last line is coming from afterCompletion() method of our interceptor

This explains clearley that, before processing our request, interceptor’s preHandle() method gets executed,
then our request will be processed,
then postHandle() method will be called ,
after that view will be rendered,
then afterCompletion() method will be called.

Download this project SpringInterceptors.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on