Spring Learning: Interceptor

Interceptor in SpringMVC is similar to the Filter in Servlet, which is used to do some pre- and after- process. Developers can create custom Interceptors to achieve some functions.

Difference between Interceptor and Filter

Hereis the link of Filter


  • Filter is part of Servlet development and can be used in any Java Web project and can conduct filtering to any visiting requests.
  • Interceptor can only be used in SpringMVC framework. It will only intercept the visiting to Controllers and won't intercept requests to jsp/html/css/image/js

Create a Interceptor

1. create a Interceptor class. Interceptor needs to implement HandlerInterceptor


package com.siyu.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class MyInterceptor implements HandlerInterceptor {

	//if return true, then move to next interceptor
	//if false, then won't move to next interceptor
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
		System.out.println("------------Before Request Method------------");
		return true;
   }

	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
		System.out.println("------------After Request Method------------");
   }

	//execute after dispatcherServlet
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
		System.out.println("------------After Completion------------");
   }
 }
				

2. Setup config of Interceptor in SpringMVC


 < mvc:interceptors>
	 < mvc:interceptor>
		 < mvc:mapping path="/**"/>
		 < bean class="com.siyu.interceptor.MyInterceptor"/>
	 < /mvc:interceptor>
 < /mvc:interceptors>
				

3. Create a Controller handle request


package com.siyu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//create a controller to test interceptor
@Controller
public class InterceptorController {

	@RequestMapping("/interceptor")
	@ResponseBody
	public String testFunction() {
		System.out.println("the function in Controller is executed");
		return "hello";
	}
}