Share on Google+Share on Google+

Spring Interceptor Example

In this tutorial you will learn about the spring Interceptor

Spring Interceptor Example

An example of interceptor is given below that prints all the Log information on the console

To use interceptor in your application do the following steps

1. Write a class that extends HandlerInterceptorAdapter class and overrride the method
(a) preHandle
(b) postHandle
(c) afterCompletion

Consider the class given below

package net.roseindia.interceptor;

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

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class MyInterceptor extends HandlerInterceptorAdapter {
	private static final Logger logger = Logger.getLogger(MyInterceptor.class);
	static {

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("\n\n preHandle \n");
		return super.preHandle(request, response, handler);

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		super.postHandle(request, response, handler, modelAndView);

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("\n\n afterCompletion \n");
		super.afterCompletion(request, response, handler, ex);


Then map the above class in the dispatcher-servlet.xml as

<bean id="handlerMapping"
	p:interceptors-ref="myInterceptor" />

<bean id="myInterceptor" class="net.roseindia.interceptor.MyInterceptor" />

An example is given below that print the DEBUG log data on the console

Download Select Source Code



Posted on: November 22, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null