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)!
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.