In this tutorial you will learn about the Interceptors in Spring
In this tutorial you will learn about the Interceptors in SpringThe 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
MyInterceptor.java
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 { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("\nBefore Hadling Request"); return super.preHandle(request, response, handler); } @Override 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); } @Override 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" />