Wednesday, December 3, 2008

Spring, Filters and Configuration easier than you think.

So I needed to add a filter for some cool stuff in my application.

First off I needed to get my filter to play nicely with Spring, so I needed to do the following in my web.xml

<filter>
<filter-name>myCoolNewFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>myCoolNewFilterSpringBean</param-value>
</init-param>
</filter>

So then I go ahead and open up my applicationContext.xml file and wire up the bean like normal

<bean name="myCoolNewFilterSpringBean" class="com.mycompany.filter.MyCoolNewFilter" />

Notice that the bean name in the app context matches the param-value in the filter config: myCoolNewFilterSpringBean

Then instead of trying to do URL patterns for the config of the filter I just tried the following:

<filter-mapping>
<filter-name>myCoolNewFilterSpringBean</filter-name>
<servlet-name>dispatcher</servlet-name>
</filter-mapping>

Which maps this filter to all filter all calls being directed to my dispatcher servlet! No nasty or convoluted URL patterns... Just easily readable servlet names!

2 comments:

A. B. M. Kowser said...

thanks a lot

you saved my day.

can you say, how can i inject FilterConfig via Filter#init(Filter)

ss said...

hi kowser,
in an application we are using opensso with ldap,fo authentication and role based url access we use
DelegatingFilterProxy of spring ,but we cant login after combining
what is the solution for this,