O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required