Spring MVC handler interceptors example

Spring MVC allow you to intercept web request through handler interceptors. The handler interceptor have to implement the HandlerInterceptor interface, which contains three methods :

  1. preHandle() – Called before the handler execution, returns a boolean value, “true” : continue the handler execution chain; “false”, stop the execution chain and return it.
  2. postHandle() – Called after the handler execution, allow manipulate the ModelAndView object before render it to view page.
  3. afterCompletion() – Called after the complete request has finished. Seldom use, cant find any use case.

In this tutorial, you will create two handler interceptors to show the use of the HandlerInterceptor.

  1. ExecuteTimeInterceptor – Intercept the web request, and log the controller execution time.
  2. MaintenanceInterceptor – Intercept the web request, check if the current time is in between the maintenance time, if yes then redirect it to maintenance page.
It’s recommended to extend the HandlerInterceptorAdapter for the convenient default implementations.

1. ExecuteTimeInterceptor

Intercept the before and after controller execution, log the start and end of the execution time, save it into the existing intercepted controller’s modelAndView for later display.

File : ExecuteTimeInterceptor.java

package com.mkyong.common.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class ExecuteTimeInterceptor extends HandlerInterceptorAdapter{
	private static final Logger logger = Logger.getLogger(ExecuteTimeInterceptor.class);
	//before the actual handler will be executed
	public boolean preHandle(HttpServletRequest request, 
		HttpServletResponse response, Object handler)
	    throws Exception {
		long startTime = System.currentTimeMillis();
		request.setAttribute("startTime", startTime);
		return true;
	//after the handler is executed
	public void postHandle(
		HttpServletRequest request, HttpServletResponse response, 
		Object handler, ModelAndView modelAndView)
		throws Exception {
		long startTime = (Long)request.getAttribute("startTime");
		long endTime = System.currentTimeMillis();
		long executeTime = endTime - startTime;
		//modified the exisitng modelAndView
		//log it
		   logger.debug("[" + handler + "] executeTime : " + executeTime + "ms");

2. MaintenanceInterceptor

Intercept before the controller execution, check if the current time is in between the maintenance time, if yes then redirect it to maintenance page; else continue the execution chain.

File : MaintenanceInterceptor.java

package com.mkyong.common.interceptor;
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class MaintenanceInterceptor extends HandlerInterceptorAdapter{
	private int maintenanceStartTime;
	private int maintenanceEndTime;
	private String maintenanceMapping;
	public void setMaintenanceMapping(String maintenanceMapping) {
		this.maintenanceMapping = maintenanceMapping;
	public void setMaintenanceStartTime(int maintenanceStartTime) {
		this.maintenanceStartTime = maintenanceStartTime;
	public void setMaintenanceEndTime(int maintenanceEndTime) {
		this.maintenanceEndTime = maintenanceEndTime;
	//before the actual handler will be executed
	public boolean preHandle(HttpServletRequest request, 
			HttpServletResponse response, Object handler)
	    throws Exception {
		Calendar cal = Calendar.getInstance();
		int hour = cal.get(cal.HOUR_OF_DAY);
		if (hour >= maintenanceStartTime && hour <= maintenanceEndTime) {
			//maintenance time, send to maintenance page
			return false;
		} else {
			return true;

3. Enable the handler interceptor

To enable it, put your handler interceptor class in the handler mapping “interceptors” property.

<beans xmlns="http://www.springframework.org/schema/beans"
	<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
				<prop key="/welcome.htm">welcomeController</prop>
		<property name="interceptors">
				<ref bean="maintenanceInterceptor" />
				<ref bean="executeTimeInterceptor" />
		<property name="interceptors">
				<ref bean="executeTimeInterceptor" />
	<bean id="welcomeController" 
                  class="com.mkyong.common.controller.WelcomeController" />
	<bean class="com.mkyong.common.controller.MaintenanceController" />
	<bean id="executeTimeInterceptor" 
                 class="com.mkyong.common.interceptor.ExecuteTimeInterceptor" />
	<bean id="maintenanceInterceptor" 
		<property name="maintenanceStartTime" value="23" />
		<property name="maintenanceEndTime" value="24" />
		<property name="maintenanceMapping" value="/SpringMVC/maintenance.htm" />
	<bean id="viewResolver"
		<property name="prefix">
		<property name="suffix">

Download Source Code


  1. HandlerInterceptorAdapter documentation
  2. HandlerInterceptor documentation
  3. ControllerClassNameHandlerMapping example
  4. SimpleUrlHandlerMapping example
Tags :

About the Author

Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.


  • Pingback: he has a good point()

  • Pingback: water ionizer loans()

  • Pingback: great post to read()

  • Pingback: alkaline water()

  • Pingback: alkaline water brands()

  • Pingback: plan()

  • Pingback: part p electricians huddersfield()

  • Pingback: electrician's fish tape()

  • Pingback: house blue()

  • Pingback: zak?ad szklarski piotrk√≥w trybunalski()

  • Pingback: paypal loans()

  • Pingback: helpful resources()

  • Pingback: level 1 electrician jobs()

  • Pingback: water ionizer plans()

  • Pingback: pay per day loan plans()

  • Pingback: car parking()

  • Pingback: water ionizer machine()

  • Pingback: water ionizer()

  • Pingback: laan penge nu sms()

  • Pingback: car parking()

  • Pingback: fue()

  • Pingback: lan penge online nu()

  • Pingback: Direct TV vs Cable TV()

  • Pingback: Sat TV()

  • Pingback: DIRECTV for your company()

  • Pingback: uk online casinos()

  • Pingback: Why Use VPN in Saudi Arabia?()

  • Pingback: kangen()

  • Pingback: kangen water machine()

  • Pingback: water purification systems()

  • Pingback: water ionizers()

  • Pingback: watch movies online()

  • Pingback: watch tv show episodes()

  • Pingback: Blue Coaster33()

  • http://[email protected] Majid

    I just downloaded the source code , imported it in eclipse, can you please tell me how to run it , should I call one of the jsp files or what ?

    • http://[email protected] Majid

      I called :

      but I got :
      HTTP Status 404 –

      WARN PageNotFound:1077 – No mapping found for HTTP request with URI [/SpringMVC/WelcomePage.htm] in DispatcherServlet with name ‘mvc-dispatcher’

      Thanks, your help is appreciated.

  • Don Good

    Once again you have posted exactly what I was looking for! Great job!

  • Mohan

    To the point for a quick reference

  • vijayaraj

    Its good example..

    • http://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/ RAJA

      Good example

  • http://www.technicalkeeda.com Yashwant Chavan

    Great tutorial mkyong

  • Pingback: Override ‘Display Intranet sites in Compatibility View’ « Karan Sachdeva()

  • Somabrata

    I want to configure my Interceptor for all the urls, My xml configuration is like this:

    &lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    	&lt;bean class=&quot;org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping&quot; /&gt;
        &lt;bean class=&quot;org.springframework.web.servlet.handler.SimpleUrlHandlerMapping&quot;&gt;
            &lt;property name=&quot;mappings&quot;&gt;
                      &lt;prop key=&quot;/mylink1.html&quot;&gt;mylink1&lt;/prop&gt;
                      &lt;prop key=&quot;/mylink2.html&quot;&gt;mylink2&lt;/prop&gt;
            &lt;property name=&quot;interceptors&quot;&gt;
    				&lt;ref bean=&quot;myInterceptor&quot; /&gt;
        &lt;bean id=&quot;myInterceptor&quot; class=&quot;correct.class.path.MyInterceptor&quot;&gt;
        &lt;bean name=&quot;mylink1&quot;
            &lt;property name=&quot;viewName&quot; value=&quot;MyLink1&quot; /&gt;   
        &lt;bean name=&quot;mylink2&quot;
            &lt;property name=&quot;viewName&quot; value=&quot;MyLink2&quot; /&gt;   
        &lt;bean class=&quot;package.MyController&quot;&gt;
            &lt;property name=&quot;formView&quot; value=&quot;MyApp&quot; /&gt;

    For mylink1.html and mylink2.html MyInterceptor is being fired,
    For myapp.html MyController is fired but not the MyInterceptor,
    I tried with,

    &lt;property name=&quot;mappings&quot;&gt;
                      &lt;prop key=&quot;/mylink1.html&quot;&gt;mylink1&lt;/prop&gt;
                      &lt;prop key=&quot;/mylink2.html&quot;&gt;mylink2&lt;/prop&gt;
                      &lt;prop key=&quot;/myapp.html&quot;&gt;myApp&lt;/prop&gt;


        &lt;bean name=&quot;myApp&quot; class=&quot;package.MyController&quot;&gt;
            &lt;property name=&quot;formView&quot; value=&quot;MyApp&quot; /&gt;

    Then also interceptor is not being fired.
    I know how to do it with spring-beans-3.0.xsd and spring-mvc-3.0.xsd but i have to stay with 2.5 version

  • Vikas

    I want to use interceptor as SignInInterceptor (or say Filter). I have defined same by extending HandlerInterceptorAdapter.

    Note that I’m using tiles2.TilesViewResolver and using Annotation for Controllers.

    &lt;bean id=&quot;viewResolver&quot; class=&quot;org.springframework.web.servlet.view.tiles2.TilesViewResolver&quot; &gt;
    	&lt;property name=&quot;viewClass&quot; value=&quot;org.springframework.web.servlet.view.tiles2.TilesView&quot; /&gt;
    &lt;bean id=&quot;tilesConfigurer&quot; class=&quot;org.springframework.web.servlet.view.tiles2.TilesConfigurer&quot;&gt;
    	&lt;property name=&quot;definitions&quot;&gt;
    &lt;bean id=&quot;authenticationInterceptor&quot; class=&quot;com.abc.AuthenticationInterceptor&quot; /&gt;

    Now, I’m not having clue regarding how to configure and use this interceptor?

    • http://nomsdom.blogspot.com Gagan
                  &lt;mvc:mapping path=&quot;/**&quot;/&gt;
                  &lt;bean class=&quot;com.abc.AuthenticationInterceptor&quot;/&gt;

      Please try above configuration . This should help.

  • Sylar

    Great tutorial on HI, mkyong.. Keep up the good work..please provide EJB tutorials too.. Would be helpful..

  • http://sumitju03203.blogspot.com Sumit Bhowmick

    Great. It’s a nice Spring interceptor tutorial.

  • Pingback: Spring MVC Tutorial()