• Filters are java components that can be used to process or intercept request from client to server before the request is sent to filter or to process responses after the servlet has completed its job and before this response reaches the client.
  • Deployment descriptor defines when to kick in filters.
  • Filters implement the Filter java interface.
  • Filters when used to intercept request can perform security checks, reformat request headers or bodies and can audit or log requests
  • Filters when used to process responses can compress the response stream, alter the response stream and can create a different response stream together.
  • Filters can also be chained together. Deployment descriptor will define the order in which they run.
  • Filters have a doFilter() method that the implementing class overwrites.
  • The container manages the life cycle of the filter. In many ways, Filter is like Servlet in characteristic.
  • Every filter can have access to ServletContext from its FilterConfig Object.

Filter’s Life Cycle:

  • Every filter must implement init(), do Filter() and destroy() methods.
  • Init(): This is where you do any set up tasks. The most common implementation is as follows

Public void init(FilterConfig config) throws ServletException{

// you can store config object of type FilterConfig in a variable to use it     // will get the servlet context from this config object


  • doFilter(): This is the method that gets called when ever the container determines that the filter should be applied to cureent request or response. It takes three arguments. They are ServletRequest, a ServletResponse and a FilterChain.This is where you implement your filter functionality.
  • Destroy(): called when the container decides to remove the instance. You can do any clean up work here.

How to Declare and order Filters?

Declaring a filter









Declaring a filter mapping to a URL pattern





Declaring a filter mapping to a servlet name






Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s