17

Using Spring 3.0.2.RELEASE. I'm having 2 Controllers in package com.myCompany. The Controllers are activated via Component-scan

<context:component-scan base-package="com.myCompany" />

then I'm having a interceptor bind to the 2 controllers via

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
   <property name="interceptors">
     <list>
       <ref bean="myInterceptor"/>
     </list>
   </property>
 </bean>

How can i bind the interceptor to only one specific Controller or to only certain methods inside a Controller? Background: I want to inspect the URL that it contains certain parameters

Docu Link

skaffman
  • 398,947
  • 96
  • 818
  • 769
Martin Dürrmeier
  • 1,653
  • 5
  • 18
  • 35
  • Check also [this solution](http://karthikg.wordpress.com/2009/10/12/athandlerinterceptor-for-spring-mvc/) with use of custom annotation. – dma_k Nov 27 '12 at 10:42

1 Answers1

20

When you inject interceptors into a HandlerMapping bean, those interceptors apply to every handler mapped by that HandlerMapping. That was fine in the pre-annotation days, since you'd just have configure multiple HandlerMapping beans. However, with annotations, we tend to have a single DefaultAnnotationHandlerMapping that maps everything, so this model doesn't work.

The solution is to use <mvc:interceptors>, where you explicitly map paths to interceptor beans. See the docs, and this example:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/secure/*"/>
        <bean class="org.example.SecurityInterceptor" />
    </mvc:interceptor>
</mvc:interceptors>
Shafin Mahmud
  • 3,831
  • 1
  • 23
  • 35
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Thanks. But i don't get it. Can I add the snippet into the File containing " ? Then I get "org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:interceptors'." I added xmlns:mvc="http://www.springframework.org/schema/mvc" – Martin Dürrmeier Aug 12 '10 at 17:14
  • @Martin: See the fixed link to the docs. You need add the `schemaLocation` in addition to the namespace. – skaffman Aug 12 '10 at 17:20
  • Thanks skaffman. It works! I've overseen the link.. What Spring sources do you recommend for getting more involved? – Martin Dürrmeier Aug 12 '10 at 17:42
  • @Martin: Hard to say. I've been using Spring since 1.2.8, so I've kind of grown with it. I still think the reference manual is excellent, though. – skaffman Aug 12 '10 at 18:07
  • So, can't I map an interceptor to some controller? Just mapping by path is available? – Sanghyun Lee Sep 01 '11 at 08:26
  • 3
    i think you should change the mapping tag to mvc:mapping. ` ` – rohtakdev Sep 07 '12 at 19:53