Accessing Spring beans from servlet filters and tags

前端 未结 4 2012
南方客
南方客 2020-12-28 14:50

I can access Spring beans in my Servlets using

WebApplicationContext springContext = 
    WebApplicationContextUtils.getWebApplicationContext(getServle         


        
相关标签:
4条回答
  • 2020-12-28 15:16

    For filters - use Filter.init():

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

    For tags - use TagSupport.pageContext (note that it's not available in SimpleTagSupport):

    WebApplicationContext springContext = 
        WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
    
    0 讨论(0)
  • 2020-12-28 15:34

    There are a couple ways to get it

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

    2. WebApplicationContext springContext = RequestContextUtils.getWebApplicationContext(servletRequest)

    then

    springContext.getBean("myBeanId");
    
    0 讨论(0)
  • 2020-12-28 15:37

    You can put all your beans as request attributes by using the ContextEsposingHttpServletRequest wrapper.

    0 讨论(0)
  • 2020-12-28 15:40

    you can use a DelegatingFilterProxy as mentioned in Spring documentation: http://static.springsource.org/spring-security/site/docs/3.0.x/reference/security-filter-chain.html#delegating-filter-proxy

    You just have to declare your real Filter bean with the same bean name as the filter-name declared in web.xml:

    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" />  
    
    0 讨论(0)
提交回复
热议问题