Vous êtes sur la page 1sur 14



ADVANCED JAVA(2160707): A.Y. 2017-18


KUNAL PARIKH - 160010116023
HARSHIL PATEL - 160010116038
LAJJA PATEL - 160010116041
B.E (IT) – SEM 6


A filter is an object that can transform a request or modify a

response. Filters are not servlets; they don't actually create a
response. They are preprocessors of the request before it reaches a
servlet, and/or postprocessors of the response leaving a servlet.

Servlet and JSP Filters are Java classes that can be used in Servlet
and JSP Programming for the following purposes:

 To intercept requests from a client before they access a resource at

back end.
 To manipulate responses from server before they are sent back to
the client
JSP - filters
There are are various types of filters suggested by the specifications:

• Authentication Filters.
• Data compression Filters
• Encryption Filters .
• Filters that trigger resource access events.
• Image Conversion Filters .
• Logging and Auditing Filters.
• MIME-TYPE Chain Filters.
• Tokenizing Filters .
• XSL/T Filters That Transform XML Content.
Filters can perform many different types of functions :

• Authentication-Blocking requests based on user identity.

• Logging and auditing-Tracking users of a web application.
• Image conversion-Scaling maps, and so on.
• Data compression-Making downloads smaller.
• Localization-Targeting the request and response to a particular locale.
• XSL/T transformations of XML content-Targeting web application
responses to more that one type of client.
These are just a few of the applications of filters. There are many more, such as
encryption, tokenizing, triggering resource access events, mime-type chaining,
and caching.
Filters are deployed in the deployment descriptor file web.xml and then map to
either servlet or JSP names or URL patterns in your application's deployment
descriptor. The deployment descriptor file web.xml can be found in <Tomcat-
installation-directory>\conf directory.

When the web container starts up your web application, it creates an instance of
each filter that you have declared in the deployment descriptor. The filters
execute in the order that they are declared in the deployment descriptor.

A filter is simply a Java class that implements the javax.servlet.Filter interface.

The javax.servlet.Filter interface defines three methods:

Method & Description
1 public void doFilter (ServletRequest, ServletResponse, FilterChain)
This method is called by the container each time a request/response pair is passed through the
chain due to a client request for a resource at the end of the chain. Performs the actual filtering

2 public void init(FilterConfig filterConfig)

This method is called by the web container to indicate to a filter that it is being placed into
service. Called before the filter goes into service, and sets the filter's configuration object

3 public void destroy()

This method is called by the web container to indicate to a filter that it is being taken out of
service. Called after the filter has been taken out of service.
The filter API is defined by the Filter, FilterChain, and FilterConfig
interfaces in the javax.servlet package. You define a filter by
implementing the Filter interface. A filter chain, passed to a filter by
the container, provides a mechanism for invoking a series of filters.
A filter config contains initialization data.

The most important method in the Filter interface is the doFilter

method, which is the heart of the filter. This method usually
performs some of the following actions:

 Examines the request headers

 Customizes the request object if it wishes to modify request

headers or data or block the request entirely

 Customizes the response object if it wishes to modify response

headers or data
 Invokes the next entity in the filter chain. If the current filter is the last
filter in the chain that ends with the target servlet, the next entity is the
resource at the end of the chain; otherwise, it is the next filter that
was configured in the WAR. It invokes the next entity by calling the
doFilter method on the chain object (passing in the request and
response it was called with, or the wrapped versions it may have
created). Alternatively, it can choose to block the request by not
making the call to invoke the next entity. In the latter case, the filter is
responsible for filling out the response.

 Examines response headers after it has invoked the next filter in the

 Throws an exception to indicate an error in processing

In addition to doFilter, you must implement the init and destroy

methods. The init method is called by the container when the filter
is instantiated.
Following is the JSP Filter Example that would print the clients IP address and current
date time each time it would access any JSP file. This example would give you basic
understanding of JSP Filter, but you can write more sophisticated filter applications
using the same concept:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Implements Filter class

public class LogFilter implements Filter {
public void init(FilterConfig config)
throws ServletException{
// Get init parameter
String testParam = config.getInitParameter("test-param");

//Print the init parameter

System.out.println("Test Param: " + testParam);
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws java.io.IOException, ServletException {
// Get the IP address of client machine.
String ipAddress = request.getRemoteAddr();

// Log the IP address and current timestamp.

System.out.println("IP "+ ipAddress + ", Time "
+ new Date().toString());

// Pass request back down the filter chain

public void destroy( ){
/* Called before the Filter instance is removed
from service by the web container*/

Compile LogFilter.java in usual way and put your LogFilter.class class file in
Filters are defined and then mapped to a URL or JSP file name, in much
the same way as Servlet is defined and then mapped to a URL pattern in
web.xml file. Create the following entry for filter tag in the deployment
descriptor file web.xml
<param-value>Initialization Paramter</param-value>
The above filter would apply to all the servlets and JSP because we
specified /* in our configuration. You can specify a particular servlet or
JSP path if you want to apply filter on few servlets or JSP’s only.

Now try to call any servlet or JSP in usual way and you would see
generated log in your web server log. You can use Log4J logger to log
above log in a separate file.
Your web application may define several different filters with a specific purpose.

<param-value>Initialization Parameter</param-value>

<param-value>Initialization Parameter</param-value>


The order of filter-mapping elements in web.xml determines the order in which the web
container applies the filter to the servlet. To reverse the order of the filter, you just need to
reverse the filter-mapping elements in the web.xml file.

For example, above example would apply LogFilter first and then it would apply
AuthenFilter to any servlet but the following example would reverse the order: