【问题标题】:spring java based - adding of filter基于spring java - 添加过滤器
【发布时间】:2014-11-17 14:52:50
【问题描述】:

为了在 xml 中添加一个 cors 过滤器,我们会在 web.xml 中做这样的事情:

  <filter>
    <filter-name>cors</filter-name>
    <filter-class>MyCorsFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/secured/*</url-pattern>
  </filter-mapping>

但是我们现在是基于 java 的配置,我们如何以编程方式实现呢?

【问题讨论】:

  • 你是如何配置你的容器的?

标签: java spring cors web.xml


【解决方案1】:

如果我对您的理解正确,您说的是基于 java 的 spring 配置。我们也在使用基于 Java 的配置,但仍在使用 web.xml。您必须将 Java 配置文件添加为 web.xml 中的上下文参数,如下所示:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.spring.AppConfig</param-value>
</context-param>

因此,您仍然可以像上面那样添加过滤器。

或者,如果您使用 WebApplicationInitializer 来配置 ServletContext,您可以执行以下操作:

public class WebAppInitializer implements WebApplicationInitializer {  

    @Override  
    public void onStartup(ServletContext container) throws ServletException {  
        container.addFilter("fooFilter", FooFilter.class); 
    }
}

编辑:在评论中回答问题 - 请记住,我以前从未这样做过,但通过查看 ServletContextFilterRegistration 的文档,我建议尝试这样做以获得映射到特定 URL 的过滤器:

container.getFilterRegistration("fooFilter")
    .addMappingForUrlPatterns(DispatcherType.REQUEST, true, "/secured/");

【讨论】:

  • 嗨@Ben,谢谢,我明天试试WebAppInitializer。如何指定过滤器将应用于哪个 url?例如。我只希望我的过滤器用于以 /secured/* 开头的请求
猜你喜欢
  • 2018-09-14
  • 2018-02-17
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 2014-09-04
相关资源
最近更新 更多