Home Tutorial Spring Spring3 Web Spring Interceptor Example


Share on Google+Share on Google+
Spring Interceptor Example
Posted on: August 30, 2012 at 12:00 AM
In this tutorial you will learn about the Interceptors in Spring

Spring Interceptor Example

The Spring interceptor have the ability to pre-handle and post-handle the request comming from the client. To write a interceptor class you need to extend the HandlerInterceptorAdapter class and you can override any of the methods given below.

1. preHandle()

2. postHandle() and

3. afterCompletion().

The following is common interceptor class given below


package roseindia.interceptor;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class MyInterceptor extends HandlerInterceptorAdapter {

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		System.out.println("\nBefore Hadling Request");
		return super.preHandle(request, response, handler);

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("\nAfter Hadling Request");
		super.postHandle(request, response, handler, modelAndView);

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception)
			throws Exception {
		System.out.println("\nAfter Rendering View");
		super.afterCompletion(request, response, handler, exception);


Now you need to map this interceptor class in dispatcher-servlet.xml as

<bean id="myInterceptor" class="roseindia.interceptor.MyInterceptor" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" p:interceptors-ref="myInterceptor" />

Download Complete Web Application


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: August 30, 2012

Recommend the tutorial

Advertisements Advertisements