How to configure Interceptors in Spring MVC / Configuring interceptor in a Spring Application

What is Interceptor?

An interceptor in a web application is a component which is the first to receive a request. All requests to the application first arrive at the interceptor if the application has an interceptor configured. Besides, the request also arrives at the interceptor after it is processed by the application and before the response is returned to the client.

Spring support for Interceptors

Spring MVC provides support for configuring an interceptor into a web application very easily. Following steps are required :

  1. Create a class which shall be acting as your interceptor. This class should extend org.springframework.web.servlet.handler.HandlerInterceptorAdapter class.
  2. Implement preHandle(), postHandle() and afterCompletion() methods of this class into your class as per the functionality of the interceptor.
  3. preHandle() method is required if the interceptor should add some functionality before the request is handled by the application. If this method returns true, the request is forwarded to the application else returned back. postHandle() method is required if the interceptor performs a task before the response is sent to the client and afterCompletion() method is required if the interceptor should do something after the response is sent to the client. None of these methods is compulsory.
  4. Declare your interceptor class as a bean in spring configuration file under the tag <mvc:interceptors>.

Scenario for Usage

Suppose you want your application to respond to requests whose url ends with myapp else return an error page. This can be easily accomplished using an Interceptor. Following section will guide you how to configure an interceptor in a Spring application and implement this functionality.

Configuring Interceptor

Create a class named ApplicationInterceptor and implement the request handling logic it its preHandle method.

package com.codippa.interceptor.ApplicationInterceptor
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
public class ApplicationInterceptor extends HandlerInterceptorAdapter {
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
                          Object handler) throws Exception {
        // get the url of request
        String uri = request.getRequestURI();
        //check if it has myapp at the end
        if (uri.endsWith("myapp")) {
            //forward request to the application 
            return true;
        }
        // else show error page
        response.sendRedirect("/error.jsp");
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, 
                        Object handler, ModelAndView modelAndView) throws IOException {
	System.out.println("Request handled");
    }
}

Each request first arrives the preHandle method of the interceptor class which gets the uri from which the request has arrived. It checks if the uri ends with the string myapp and returns true or false accordingly. Note that if the preHandle method of interceptor returns true, the request is forwarded to the application else it is returned back.
After the request is handled by the application, it arrives to the postHandle method which outputs the string Request handled which get printed in the server log file.

Declare this class as a bean in your application’s Spring context file as below :

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans”
    xmlns:context=”http://www.springframework.org/schema/context”
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:mvc=”http://www.springframework.org/schema/mvc”
    xmlns:tx=”http://www.springframework.org/schema/tx” xmlns:p=”http://www.springframework.org/schema/p”
    xsi:schemaLocation=”
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd”>

   <mvc:interceptors>
        <bean class=”com.codippa.interceptor.ApplicationInterceptor” />
    </mvc:interceptors>

<bean
        class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
        <property name=”prefix” value=”/WEB-INF/views/jsp/” />
        <property name=”suffix” value=”.jsp” />
</bean>

  </beans>

Let’s tweak in

  1. There can be multiple interceptors in a single application. They are invoked in the order in which they are declared in the configuration file.
  2. preHandle methods of all the interceptors are called in the order in which they are declared in the configuration file while postHandle and afterCompletion methods are called in the reverse order, that is, methods of last declared interceptor are called first and that of first interceptor are called last.
  3. afterCompletion method is called after the view is rendered and is called only if preHandle method executed successfully(returned true).
  4. Interceptor configuration using <mvc:interceptors> has been introduced in Spring 3.0. In earlier versions, interceptors were required to be added using addInterceptor method of org.springframework.web.servlet.config.annotation.InterceptorRegistry class.
  5. If the interceptor class is added but does not work, there are chances that it is not declared under <mvc:interceptors> tag in Spring configuration file.

Mark Your Impression

Close Menu