代码之家  ›  专栏  ›  技术社区  ›  Damien

从servlet过滤器和标签访问SpringBean

  •  25
  • Damien  · 技术社区  · 15 年前

    我可以使用

    WebApplicationContext springContext = 
        WebApplicationContextUtils.getWebApplicationContext(getServletContext()); 
    

    在伺服系统中 init 方法。

    我想知道是否有一个相当于 WebApplicationContext 对于servlet过滤器? 另外,是否可以在标记类中访问SpringBean?

    4 回复  |  直到 11 年前
        1
  •  38
  •   axtavt    15 年前

    用于过滤器-使用 Filter.init() :

    public void init(FilterConfig config) {
        WebApplicationContext springContext = 
            WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
    }
    

    用于标签-使用 TagSupport.pageContext (请注意,在 SimpleTagSupport ):

    WebApplicationContext springContext = 
        WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
    
        2
  •  26
  •   Alexis K    15 年前

    可以使用委托过滤器代理,如Spring文档中所述: http://static.springsource.org/spring-security/site/docs/3.0.x/reference/security-filter-chain.html#delegating-filter-proxy

    您只需使用与web.xml中声明的过滤器名称相同的bean名称声明真正的过滤器bean:

    Web.xml:

        <filter>
           <filter-name>SpringTestFilter</filter-name>
           <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        </filter>
    
        <filter-mapping>
           <filter-name>SpringTestFilter</filter-name>
           <url-pattern>/*</url-pattern>
        </filter-mapping>
    

    applicationContext.xml:

        <bean id="SpringTestFilter" class="com.company.app.servlet.SpringTestFilter" />  
    
        3
  •  2
  •   Uri Agassi    11 年前

    有几种方法可以得到它

    1. WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getFilterCongig().getServletContext());

    2. WebApplicationContext springContext = RequestContextUtils.getWebApplicationContext(servletRequest)

    然后

    springContext.getBean("myBeanId");
    
        4
  •  0
  •   Bozho    15 年前