【问题标题】:Is it possible to use a profile based filter in your web.xml是否可以在 web.xml 中使用基于配置文件的过滤器
【发布时间】:2012-08-02 09:51:20
【问题描述】:

是否可以在 web.xml 中使用基于配置文件的过滤器?例如

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
         <init-param>
            <param-name>spring.profiles.active</param-name>
            <param-value>secured</param-value>
        </init-param>
    </filter>

我知道这对于 servlet 是可能的,但我似乎无法让它对过滤器起作用。

谢谢

【问题讨论】:

    标签: java servlets spring-security web.xml


    【解决方案1】:

    原答案

    过滤器使用从 ContextLoaderListener 加载的 ApplicationContext,因此不使用过滤器的&lt;init-param&gt;。相反,您将希望使用其中一种激活 ContextLoaderListener 的配置文件的方法。一种方法是使用如下所示的:

    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>secured</param-value>
    </context-param>
    

    跟进

    根据 cmets 进行跟进。没有办法使用 Spring 配置文件省略过滤器,因为 web.xml 将始终加载 DelegatingFilterProxy,它总是尝试加载其委托。如果委托丢失,您将收到错误消息。相反,您可以创建一个禁用 Spring Security 的配置文件,如下所示:

    <b:beans profile="default,secured">
      <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
      </http>
      <authentication-manager>
        <authentication-provider>
          <user-service>
            <user name="user" password="password" authorities="ROLE_USER" />
          </user-service>
        </authentication-provider>
      </authentication-manager>
    </b:beans>
    <b:beans profile="insecure">
      <http security="none" />
    </b:beans>
    

    然后您可以通过激活 web.xml 中的不安全配置文件来禁用 Spring Security,如下所示。

    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>insecure</param-value>
    </context-param>
    

    如果您没有使用 Spring Security,您可以通过创建一个过滤器来禁用过滤器,该过滤器除了继续过滤器链并将其放置在禁用的配置文件中之外什么都不做。例如:

    public class DoFilterChainFilter implements Filter {
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            chain.doFilter(request, response);
        }
        public void destroy() { }
        public void init(FilterConfig filterConfig) throws ServletException { }
    }
    

    【讨论】:

    • 谢谢。所以不可能只在某些配置文件中实例化过滤器?
    • 我不确定我是否理解这个问题。配置文件将影响整个配置,但您只能通过使用过滤器配置文件来影响过滤器。
    • 是的,但假设我希望配置文件确定是否实例化过滤器。
    • 我仍然不确定我是否理解。该问题询问是否可以使用基于配置文件的过滤器。如果您想完全禁用它,您是在问配置应该是什么样子?
    • 是的,有点。显然,可以根据配置文件为过滤器类实例化 2 个不同的 bean。正如您所说,这取自上下文参数。想象一下,如果您希望在配置文件未激活时禁用过滤器。配置是什么样的?
    猜你喜欢
    • 2015-05-31
    • 2015-08-28
    • 2012-12-05
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 2012-02-05
    • 2010-10-31
    • 1970-01-01
    相关资源
    最近更新 更多