Spring MVC Interceptor Example – XML and Annotation Java Config

In this Spring tutorial, we will learn to use spring mvc interceptor in spring mvc applications. This tutorial is very short to focus only on spring interceptor configuration and usage.

Interceptors, as we know, are special web programming constructs which gets invoked every time when a certain pre-configured web request is made. They are always the most important and basic functional segments designed very early in product life cycle, due to their importance.

Interceptors are generally used do some processing before handing it over to the controller handler methods.

1. Create Spring MVC Interceptor

1.1. Spring mvc interceptor by implementing HandlerInterceptor

HandlerInterceptor interface defined 3 methods.

  1. preHandle(request, response, handler) – Used to intercept the request before handed over to the handler method. Here handler is the chosen handler object to handle the request.
  2. postHandle(request, response, handler, modelAndView) – Used to intercept the request after handler has completed request processing but DispatcherServlet is yet to render the view.
  3. afterCompletion(request, response, handler, exception)
  4. – It is called once the handler execution is complete and view is rendered as well.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class DemoInterceptor implements HandlerInterceptor
{
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		System.out.println("Inside pre handle");
		return true;
	}

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

		System.out.println("Inside post handle");
	}

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

		System.out.println("Inside after completion");
	}
}

1.2. Spring interceptor by extending HandlerInterceptorAdapter

HandlerInterceptorAdapter is abstract adapter class for the HandlerInterceptor interface.

It helps us in implementing only required pre or post handler method. We are not forced to implement all the methods. All the default implementations of methods in this abstract class are ’empty’.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.ModelAndView;

public class DemoInterceptor extends HandlerInterceptorAdapter
{
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		System.out.println("Inside pre handle");
		return true;
	}

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

		System.out.println("Inside post handle");
	}
}

2. Spring interceptor example

2.1. Spring web maven dependency

Add Spring 5 web dependency to create Spring MVC application.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.0.6.RELEASE</version>
</dependency>

2.2. Write spring interceptor

package com.howtodoinjava.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 DemoInterceptor implements HandlerInterceptor
{
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		System.out.println("Inside pre handle");
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("Inside post handle");
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception)
			throws Exception {
		System.out.println("Inside after completion");
	}
}

2.3. Configure spring interceptor in bean configuration

2.3.1. Spring interceptor XML configuration

XML configuration helps in adding path patterns on which interceptor will be invoked. Alternatively, we can configure interceptor to be invoked for all web requests.

<!-- Configures Interceptors -->
<mvc:interceptors>

	 <!-- This XML will intercept all URIs -->
	 <bean class="com.howtodoinjava.interceptor.DemoInterceptor"></bean>

	 <!-- This XML will apply interceptor to only configured URIs -->
	 <!--
	 <mvc:interceptor>
		  <mvc:mapping path="/users"></mvc:mapping>
		  <bean class="com.howtodoinjava.interceptor.DemoInterceptor"></bean>
	 <mvc:interceptor>
	  -->
</mvc:interceptors>
2.3.2. Spring interceptor Java configuration
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    DemoInterceptor demoInterceptor() {
         return new DemoInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(demoInterceptor());
    }

}

2.4. Demo

Now if we start the server and hit the URL: http://localhost:8080/firstSpringApplication/users, we will the see statements written in interceptor methods printed in console output.

Download the given source code to play with it and understand Spring MVC interceptor in more detail.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

4 thoughts on “Spring MVC Interceptor Example – XML and Annotation Java Config”

  1. Hi ,
    I have a query.
    If i am using two interceptors in my application then what is the flow of execution of these interceptors?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.