Tuesday, January 17, 2012

Java Servlet Filters

1. History
Servlet Filters are the latest components that are added in Servlet 2.3 specifications. These filters are used basically for intercepting and modifying requests and response from server.

2. Pre-requisites
We will be using 3 things here.

  1. JDK 1.6
  2. Tomcat 6
  3. Eclipse (galileo or helios)
3. Usage
The usage is very simple. This is a very basic and simple way of demonstrating the use of Java filters. First create a dynamic web project in eclipse. Then create a directory structure as shown:

As it can seen that, under "Java Resources", 
  1. A package named "com.zinnia.filter" has been created.
  2. Under that package a java class named "MyFilter.java" has been created.
Inside the "WebContent" directory, 
  • An HTML file named "index.html" has been created. 

1. Java Class:


2. HTML file(index.html)

3. Deployment descriptor:(web.xml)

4. Testing the filter:

Just right click on index.html page, hover the mouse on "Rus As", then click on "Run on Server".
  1. You must be able to view your index.html page on the browser. URL here is "http://localhost:8080/FilterExample/index.html".
  2. Next, navigate to the page "http://localhost:8080/FilterExample/index.html?redirectme=abc". This time the filter catches the "redirectme" using getParameterValues and redirect the browser to "http://www.google.com".
Try out different possibilities of using filters. In my view, this is one of the powerful tool or way to redirect url requests. Enjoy using Java Filters!!!!!..

No comments:

Post a Comment