如何在Spring MVC 3.0中注册处理程序拦截器? [英] How to register handler interceptors with spring mvc 3.0?

查看:84
本文介绍了如何在Spring MVC 3.0中注册处理程序拦截器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该很容易:

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

但是这种方式不会调用拦截器.

but this way the interceptor isn't called.

推荐答案

默认情况下,Spring将注册BeanNameUrlHandlerMappingDefaultAnnotationHandlerMapping,而无需任何显式配置.

By default, Spring will register a BeanNameUrlHandlerMapping, and a DefaultAnnotationHandlerMapping, without any explicit config required.

如果定义了自己的HandlerMapping bean,则默认的bean将不会被注册,而您将仅获得显式声明的bean.

If you define your own HandlerMapping beans, then the default ones will not be registered, and you'll just get the explicitly declared ones.

到目前为止,很好.

当您将<mvc:annotation-driven/>添加到混合中时,问题就来了.此声明了自己的DefaultAnnotationHandlerMapping,它将替换默认值.但是,如果您还声明自己的一个,那么最终您将得到两个.由于按照声明的顺序进行查询,因此通常意味着先调用<mvc:annotation-driven/>注册的,然后忽略您自己的.

The problem comes when you add <mvc:annotation-driven/> to the mix. This also declares its own DefaultAnnotationHandlerMapping, which replaces the defaults. However, if you also declare your own one, then you end up with two. Since they are consulted in order of declaration, this usually means the one registered by <mvc:annotation-driven/> gets called first, and your own one gets ignored.

如果<mvc:annotation-driven/>注册的DefaultAnnotationHandlerMapping的行为类似于默认值,那就更好,即,如果显式声明的优先级优先,但这不是他们编写的方式.

It would be better if the DefaultAnnotationHandlerMapping registered by <mvc:annotation-driven/> acted like the default one, i.e. if explicitly declared ones took precedence, but that's not the way they wrote it.

我当前的偏好是根本不使用<mvc:annotation-driven/>,这太混乱了,与其他配置选项混合使用时也太不可预测了.它实际上并没有做任何特别复杂的事情,显式添加它为您所做的工作并不困难或冗长,并且最终结果更易于理解.

My current preference is to not use <mvc:annotation-driven/> at all, it's too confusing, and too unpredictable when mixed with other config options. It doesn't really do anything especially complex, it's not difficult or verbose to explicitly add the stuff that it does for you, and the end result is easier to follow.

这篇关于如何在Spring MVC 3.0中注册处理程序拦截器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆