views:

540

answers:

4

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?

+2  A: 

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());
axtavt
A: 

Thanks Guys, i did more digging in my code and I thought these were the solutions

Thank you for providing these answers

Damo
You're welcome, but please don't post comments (or questions) as answers. Post them as comments. Use the `add comment` link.
BalusC
A: 

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

Bozho
A: 

Hi, 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" />  
Alexis K