7

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.

Dean Peterson
  • 467
  • 6
  • 15

3 Answers3

10

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 Kunjummen
  • 49,138
  • 14
  • 112
  • 125
  • 2
    This answer turned me in the right direction thank you! I had forgotten I set up a Class using the @EnableWebMvc in my WebMvcConfig class. The following ended up working:`@Configuration @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @Inject private ConnectionRepository connectionRepository; @Override public void addInterceptors(InterceptorRegistry registry){ // Equivalent to registry.addInterceptor(new DomainNameInterceptor()); }` – Dean Peterson May 25 '12 at 02:06
  • 2
    isn't a child tag of in Spring 3.1, but is now it's own root tag. Great answer otherwise. – Emerson Farrugia Jul 03 '12 at 16:11
9

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>
SGT Grumpy Pants
  • 4,118
  • 4
  • 42
  • 64
0

This question might be old, but in case someone bumps into it looking for answers like I did, the use of a MappedInterceptor as described in the answer below worked for me.

https://stackoverflow.com/a/35948730/1705048

NDAclan
  • 43
  • 8