Suggested Pages

Saturday, May 12, 2012

Example of Spring Interceptors - Tutorial

In this post we'll see an example of a Spring Interceptor.
The Interceptor shown in this post is called LoggerInterceptor. It writes on the console before and after the Controller serves the request. Actually it writes on the console to make simple this example.

Step-1: Create Interceptor class

LoggerInterceptor class extends HandlerInterceptorAdapter and overrides preHandle, postHandle and afterCompletion.

package com.simonefolinojavablog.spring.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 LoggerInterceptor extends HandlerInterceptorAdapter {

 public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
  System.out.println("Before handling the request");
  return super.preHandle(request, response, handler);

 public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  System.out.println("After handling the request");
  super.postHandle(request, response, handler, modelAndView);

 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
   throws Exception {
  System.out.println("After rendering the view");
  super.afterCompletion(request, response, handler, ex);


Step-2: Spring Context

In the Spring Context configuration we have to activate the support to annotations. Then we have to declare the interceptor created in the first step (LoggerInterceptor) and the intercepted request paths using <mvc:interceptors/> tag as shown below.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
 xmlns:mvc="" xmlns:p=""

 <context:annotation-config />

 <context:component-scan base-package="com.simonefolinojavablog.spring.controller" />

   <mvc:mapping path="/firstcontroller/*.htm" />
   <bean id="loggerInterceptor" class="com.simonefolinojavablog.spring.interceptor.LoggerInterceptor" />

No comments :

Post a Comment

Suggested Pages