Accessing Spring beans from servlet filters and tags

爷,独闯天下 提交于 2019-11-30 12:33:19

问题


I can access Spring beans in my Servlets using

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

in the Servlet's init method.

I was wondering is there an equivalent of the WebApplicationContext for servlet filters? Also, is it possible to access Spring beans in a tag class?


回答1:


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());



回答2:


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" />  



回答3:


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");



回答4:


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



来源:https://stackoverflow.com/questions/2416671/accessing-spring-beans-from-servlet-filters-and-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!