Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 3.1 HandlerInterceptor Not being called

Tags:

java

spring

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: enter image description here

I have an annotated controller beginning like this:

enter image description here

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.

like image 333
Dean Peterson Avatar asked May 24 '12 21:05

Dean Peterson


2 Answers

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>
like image 149
Biju Kunjummen Avatar answered Oct 08 '22 11:10

Biju Kunjummen


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>
like image 32
SGT Grumpy Pants Avatar answered Oct 08 '22 13:10

SGT Grumpy Pants