Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind Spring HandlerInterceptor only to one controller

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

like image 750
Martin Dürrmeier Avatar asked Aug 12 '10 15:08

Martin Dürrmeier


People also ask

How would you implement a HandlerInterceptor in Spring boot?

To work with interceptor, you need to create @Component class that supports it and it should implement the HandlerInterceptor interface. preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client.

What is HandlerInterceptorAdapter in Spring?

Simply put, a Spring interceptor is a class that either extends the HandlerInterceptorAdapter class or implements the HandlerInterceptor interface. The HandlerInterceptor contains three main methods: prehandle() – called before the execution of the actual handler. postHandle() – called after the handler is executed.


1 Answers

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>
like image 172
skaffman Avatar answered Sep 19 '22 17:09

skaffman