I am trying learn Interceptors in spring but not able to understand it. I tried a sample example but get no success. I have created a simple interceptor like
@Co
First have a look at the Interface HandlerInterceptor it is very well documented! (HandlerInterceptorAdapter
is only a subclass that helps you if you do not want to implement all 3 methods) .
Then you will notice that there are 3 methods, each belong to one step in the "processing" chain.
Then you will notice that you used the wrong method: use postHandle
instead of preHandle
.
Then you will notice that the model map that you have created in your filter ModelAndView mv = new ModelAndView();
is not connected to something, and therefore it can not work! But fortunately postHandle
has a ModelAndView modelAndView
parameter. And you must use this instead of creating your unconnected model map.
Maybe later you will notice that you created the filter twice. Once by component scan and once by xml declaration. (In this case I would recommend to remove the @Compnent
Annotation)
So at the end your class would look like:
public class testInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView){
modelAndView.addObject("name", "test name");
}
}
At the end you will notice (I am not 100% sure) that this interceptor is not invoked for the spring security login request (j_spring_security_check) or logout. Because this is handled in a spring security filter that is applied before any HandlerInterceptor is called.
(comment) Now I can see my sysout comment when I call my login page but it is displaying it 16 times why is this so?
Maybe because you are loading some resources (images, css, js) though a controller.