A filter’s life cycle

Every filter must implement the three methods in the Filter interface: init(), doFilter(), and destroy().

First there’s init()

When the Container decides to instantiate a filter, the init() method is your chance to do any set-up tasks before the filter is called. The most common implementation was shown on the previous page; saving a reference to the FilterConfig object for later use in the filter.

doFilter() does the heavy lifting

The doFilter() method is called every time the Container determines that the filter should be applied to the current request. The doFilter() method takes three arguments:

  • A ServletRequest (not an HttpServletRequest)!

  • A ServletResponse (not an HttpServletResponse)!

  • A FilterChain

The doFilter() method is your chance to implement your filter’s function. If your filter is supposed to log user names to a file, do it in doFilter(). Want to compress the response output? Do it in doFilter().

In the end there’s destroy()

When the Container decides to remove a filter instance, it calls the destroy() method, giving you a chance to do any cleanup you need to do before the instance is destroyed.

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.