A servlet filter can be converted into a spring bean using org.springframework.web.filter.DelegatingFilterProxy.

Say, for example, your servlet filter class is Foo, then your web.xml will contain:

  <filter>
    <filter-name>foo</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>foo</filter-name>
    <url-pattern>*</url-pattern>
  </filter-mapping>

Spring configuration xml file:

  <bean name="foo" class="com.Foo">
  </bean>

Beware, there is a catch. From the api doc:

The lifecycle methods defined by the Servlet Filter interface will by default not be delegated to the target bean, relying on the Spring application context to manage the lifecycle of that bean. Specifying the “targetFilterLifecycle” filter init-param as “true” will enforce invocation of the Filter.init and Filter.destroy lifecycle methods on the target bean, letting the servlet container manage the filter lifecycle.

So, if you want the servlet container to manage filter’s life cycle, then pass targetFilterLifecycle as one of the parameters to the init method:

  <filter>
    <filter-name>foo</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
      <param-name>targetFilterLifecycle</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
Advertisements