I followed the documentation for HandlerInterceptors. Noting that in the new version of Spring: "the configured interceptor will apply to all requests handled with annotated controller methods".
The following is in an xml configuration file:
I have an annotated controller beginning like this:
When I request a url that executes the controller's code, my interceptor code is never called. Can anyone please explain why?
The interceptor code is:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class DomainNameInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler)
throws Exception {
System.out.println("Why is this not called?");
return true;
}
}
I was using the following documentation: Spring Core 3.1.x Documentation
I did a search for HandlerInterceptor and followed the example given within the documentation in the included link.
If you have configured your MVC context using <mvc:annotation-driven/>
,then I think the handlerMapping created when defining beans based on this custom namespace is overriding the handlerMapping that you have defined. A better way to register your interceptors would be to use the <mvc:interceptors>
subtag to define the interceptors, this way it will get registered to the correct handlerMapping:
<mvc:annotation-driven>
<mvc:interceptors>
<ref bean="interceptor"/>
</mvc:interceptors>
</mvc:annotation-driven>
Biju's answer above is correct except in spring 3.1 you have to do this:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/pathToIntercept/**" />
<bean class="com.foo.bar.Interceptor" />
</mvc:interceptor>
</mvc:interceptors>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With