我在Spring MVC应用的web.xml中看到了这一点:

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

我试图弄清楚为什么它存在以及是否真正需要它。

我找到了this explanation in the Spring docs,但并没有帮助我理解它:

似乎表明此组件是web.xml中定义的servlet和Spring applicationContext.xml中定义的组件之间的“胶水”。



因此,如果我从web.xml中删除它,将会发生什么?我的servlet无法与Spring容器通信?**

最佳答案

这里有些魔术,但最后,所有东西都是确定性程序。

DelegatingFilterProxy 是一个过滤器,如上所述,其目标是“委托(delegate)给实现Filter接口(interface)的Spring管理的bean”,即找到一个bean(“目标bean”或“委托(delegate)”)。在您的Spring应用程序上下文中并调用它。这怎么可能?由于此bean实现javax.servlet.Filter,因此将调用其doFilter方法。

哪个 bean 叫? “DelegatingFilterProxy”支持“targetBeanName”,在Spring应用程序上下文中指定目标Bean的名称。

正如您在web.xml中看到的一样,bean的名称是“springSecurityFilterChain”

因此,在Web应用程序的上下文中,Filter会在您的应用程序上下文中实例化一个名为“springSecurityFilterChain”的bean,然后通过doFilter()方法委托(delegate)给它。

请记住,您的应用程序上下文是使用所有的APPLICATION-CONTEXT(XML)文件定义的。例如:applicationContext.xml和applicationContext-security.xml。

因此,请尝试在后者中找到一个名为“springSecurityFilterChain” 的bean ...

...而且可能无法(例如,如果您遵循了教程或使用Roo配置了安全性)

神奇之处在于:有一个用于配置安全性的新元素,类似于

<http auto-config="true" use-expressions="true">

因为http://www.springframework.org/schema/security/spring-security-3.0.xsd允许,所以可以解决问题。

当Spring使用XML文件加载应用程序上下文时,如果找到一个元素,它将尝试建立HTTP安全性,即过滤器堆栈和 protected URL,并注册名为“springSecurityFilterChain”的FilterChainProxy。

另外,您可以以经典方式定义Bean,即:
<beans:bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">

但是不建议这样做,因为您需要做很多配置(您将要使用的所有过滤器。并且有十几个过滤器)

07-28 03:30
查看更多