Home Tutorial Spring Spring Interceptor Example

 
 

Share on Google+Share on Google+
Spring Interceptor Example
Posted on: November 22, 2011 at 12:00 AM
Advertisement
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

MyInterceptor.java

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 {
		BasicConfigurator.configure();
	}

	@Override
	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);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("\n\npostHandle\n");
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	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"
	class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"
	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

Advertisement

Related Tags for Spring Interceptor Example:


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.

Posted on: November 22, 2011

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com