Powering Java Web with Filters

First things First.. What is a Filter ? Filters are Java components that we can use to process request before they sent to servlet or process response before they sent to client. So the poor servlet doesn't know about these things.

So actually why we are using this ? What is that much of important in filters ? Here is the answer..
Suppose you want to enhance your web app by tracking the users that goes to particular servlet. So the typical answer is change the code in servlet and add necessarily things to fulfill the requirement. This is not a good choice. Because editing the servlet source code can effect on the other areas in your app. So the one and only choice is to use Filters.
In this article you will learn some basic things about filters and specially how to use filters.

Filters can be chained together, to run one after the other and its in-dependable. Filters don't know what filter before run or after.
Our Deployment Descriptor(web.xml) control the order that filters run.

Filter's Life Cycle
Every Filter Must implement 3 methods.
1. init()

  • Can do any set-up task before the filter called.
2. doFilter()

  • This method is called every time the container determines that the filter should be applied to the current request.
  • It takes 3 args.--> ServletRequest, ServletResponse, FilterChain
  • This is the method that implements all of your logic that you want to do in filter.
3. destroy()
  • Container decide to remove the filter it calls the destroy(). 
  • Can do any clean-up

Configure Filters in Deployment Descriptor(web.xml)
When we config filters in web.xml we usually do 3 things.

1.Filter Declare

<filter-name>name of the filter</filter-name>
<filter-class>class that contain filter login (ex: implement Filter interface)</filter-class>
  <param-name>para name</param-name>
  <param-value>para value</param-value>

  • <filter-name> and <filter-class> are mandatory
2. Map Filter to URL 


  <filter-name>name of the filter</filter-name>


3.Map to Servlet Name
 <filter-name>name of the filter</filter-name>
 <servlet-name>name of the servlet map name</servlet-name>

  • If the request coming from forward, include , request dispatch or error you can use this.
  • <dispatcher>FORWARD</dispatcher> or ... inside 2 nd option.
Here is some basic things about request filter. On next post I will talk about response filters and some basic example of this implementation.  KIT :)