java 仅将 Spring HandlerInterceptor 绑定到一个控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3469489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:58:04  来源:igfitidea点击:

bind Spring HandlerInterceptor only to one controller

javaspringspring-mvc

提问by Martin Dürrmeier

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

使用 Spring 3.0.2.RELEASE。我在 com.myCompany 包中有 2 个控制器。控制器通过组件扫描激活

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

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

然后我有一个拦截器绑定到 2 个控制器通过

<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

如何将拦截器仅绑定到一个特定的控制器或仅绑定到控制器内的某些方法?背景:我想检查包含某些参数的 URL

Docu Link

文档链接

回答by skaffman

When you inject interceptors into a HandlerMappingbean, 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 HandlerMappingbeans. However, with annotations, we tend to have a single DefaultAnnotationHandlerMappingthat maps everything, so this model doesn't work.

当您将拦截器注入HandlerMappingbean 时,这些拦截器适用于由该映射的每个处理程序HandlerMapping。这在预注释时代很好,因为您只需要配置多个HandlerMappingbean。但是,对于注释,我们倾向于有一个DefaultAnnotationHandlerMapping映射所有内容的单个,因此该模型不起作用。

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

解决方案是使用<mvc:interceptors>,您可以在其中显式地将路径映射到拦截器 bean。请参阅文档和此示例:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/secure/*"/>
        <bean class="org.example.SecurityInterceptor" />
    </mvc:interceptor>
</mvc:interceptors>