Вы находитесь на странице: 1из 14

A.D.

PATEL I NSTITUTE OF TECHNOLOGY


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

SERVLET FILTERS

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

GUIDED BY:
PROF NAYAN MALI
(ADIT)
JSP - FILTERS

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.
ONE OR MANY FILTERS
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.
SERVLET FILTER METHODS:

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


The javax.servlet.Filter interface defines three methods:

S.N
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
work

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.
PROGRAMMING FILTERS
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
PROGRAMMING FILTERS…CONTD
 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
chain

 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.
JSP FILTER EXAMPLE1:
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 {
EXAMPLE…..CONTD..:
// 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


chain.doFilter(request,response);
}
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
<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.
JSP FILTER MAPPING IN WEB.XML:
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
<web-app>
…..
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
……
</web-app>
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.
USING MULTIPLE FILTERS:
Your web application may define several different filters with a specific purpose.

<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Parameter</param-value>
</init-param>
</filter>

<filter>
<filter-name>AuthenFilter</filter-name>
<filter-class>AuthenFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Parameter</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
FILTERS APPLICATION ORDER:

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:

<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Вам также может понравиться