Showing posts with label filters. Show all posts
Showing posts with label filters. Show all posts

Thursday, 1 September 2011

Creating a custom filter in Spring

Adding a filter in spring is something that seems like it should be easy, but can be tricky if you get your configurations in a twist.

So here is how I added a really simple filter to my Spring application.

In my web.xml I added the following filter definition, alongside the other standard security and encoding ones:

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



The org.springframework.web.filter.DelegatingFilterProxy is the relevant filter type that allows you to then declare a targetBeanName value... which corresponds to a declaration we add in our applicationContext.xml, as so:

<bean name="expiredPasswordFilterBean" class="com.companyname.webapp.filter.ExpiredPasswordFilter"/>

With that connection set up, we now head back to the web.xml to define the mapping for our filter... separately from the above filter definition. In my case, this was enough:

 <filter-mapping>
  <filter-name>expiredPasswordFilter</filter-name>
  <url-pattern>*.html</url-pattern>
 </filter-mapping>


the filter name connects to the previous web.xml definition, and the url-pattern in my case was for the filter to be run on every request for a HTML path.

With that all in place, all I needed to do was declare the actual filter control class. This is defined in the applicationContext above as being at com.companyname.webapp.filter.ExpiredPasswordFilter, and the class looks a little like this:

com.companyname.webapp.filter.ExpiredPasswordFilter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

public class ExpiredPasswordFilter extends OncePerRequestFilter {

 protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
  
  /*
   *  This is where I did my user flag checking
   */
  
                chain.doFilter(req, res);
 }
}


The actual logic of the filter can be almost anything you want! But just make sure you call chain.doFilter(req, res); to invoke the next filter in the chain. This can be at any point throughout your code, and control is passed straight back to your filter once the chain has been executed, which can be useful for ensuring other security/authentication filters have been run before you do anything additional yourself.