Interceptor in Spring 3 MVC

Interceptors are very important to a web framework/application. MVC frameworks like Struts 2 implements most of the framework’s functionality via Interceptors.

In general intercepts are used for the purpose of implemeting User Authentication, Logging, Hibernate session management via “Open Session in View” design pattern etc. In Spring 3 we can add an interceptor by implementing HandlerInterceptor interface.

package com.bharat.spring.mvc.interceptors;

import java.util.Enumeration;

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

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoggingInterceptor implements HandlerInterceptor{

    private Logger log = Logger.getLogger(this.getClass());

    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object object, Exception exception)
            throws Exception {
        log.info("This gets executed after Completion.");

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        log.info("This method gets executed after our request is handled.");

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object object) throws Exception {
        log.info("*******************************************************");
        log.info("** Remote Address : " + request.getRemoteAddr());
        log.info("** Context Path    : " + request.getContextPath());
        log.info("** Request URI    : " + request.getRequestURI());
        Enumeration<String> attrs = request.getAttributeNames();
        while(attrs.hasMoreElements()){
            String attr = attrs.nextElement();
            log.info("** Request Attr    : " + attr +" = "+ request.getAttribute(attr));
        }
        log.info("** Request URI    : " + request.getAttributeNames());
        log.info("*******************************************************");
        return true;
    }

}

In your application’s Spring config file this is configured as below. In my example it is dispatcher-servlet.xml

<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"
	xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<!-- Interceptors -->
	<mvc:interceptors>
		<bean id="loggingInterceptor" class="com.bharat.spring.mvc.interceptors.LoggingInterceptor" />
		<!-- More interceptors go here -->
	</mvc:interceptors>
</beans>

The order of execution of interceptors is the order in which you put
between your <mvc:interceptors>…</mvc:interceptors> tag.

web.xml of you application can be configured like below.

<?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>vcs</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/*-config.xml
			/WEB-INF/dispatcher-servlet.xml
 </param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>
			org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
	<!-- Log4j config listener -->
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<!-- Spring security filter -->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!--Used to Enable Spring MVC -->
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>
Advertisements

, , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: