jump to navigation

Servlet Filters August 18, 2005

Posted by Coolguy in Servlets/Jsp.
trackback

Introduction

  • The Java Servlet specification version 2.3 introduces a new component type, called a filter
  • A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses.
  • A filter is a reusable piece of code that can transform the content of HTTP requests, responses, and header information
  • Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource
  • Filters can act on dynamic or static content

Uses of Filters

  • Filters are important for a number of reasons
  • First, they provide the ability to encapsulate recurring tasks in reusable units
  • Second, filters can be used to transform the response from a servlet or a JSP page. A common task for the web application is to format data sent back to the client. Increasingly the clients require formats (for example, WML) other than just HTML. To accommodate these clients, there is usually a strong component of transformation or filtering in a fully featured web application
  • 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.
  • Encryption filters
  • 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.
  • Filters that trigger resource access events
  • MIME-type chain filters
  • Caching filters

Filters can do the following

  • The accessing of a resource before a request to it is invoked.
  • The processing of the request for a resource before it is invoked.
  • The modification of request headers and data by wrapping the request in customized versions of the request object.
  • The modification of response headers and response data by providing customized versions of the response object.
  • The interception of an invocation of a resource after its call.
  • Actions on a servlet, on groups of servlets, or static content by zero, one, ormore filters in a specifiable order

Programming Filters

  • Programming the filter is only half the job of using filters
  • You also need to configure how they are mapped to servlets when the application is deployed in a web container. This decoupling of programming and configuration is a prime benefit of the filter mechanism
  • The filter API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package
  • A filter implements javax.servlet.Filter and defines its three methods:
  • void init(FilterConfig config) throws ServletException: Called before the filter goes into service, and sets the filter’s configuration object
  • void destroy(): Called after the filter has been taken out of service
  • void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException: Performs the actual filtering work

doFilter

  • The most important method in the Filter interface is the doFilter method, which is the heart of the filter
  • In its doFilter() method, each filter receives the current request and response, as well as a FilterChain containing the filters that still must be processed
  • In the doFilter() method, a filter may do what it wants with the request and response.
  • The filter then calls chain.doFilter() to transfer control to the next filter
  • When that call returns, a filter can, at the end of its own doFilter() method, perform additional work on the response; for instance, it can log information about the response
  • If the filter wants to halt the request processing and gain full control of the response, it can intentionally not call the next 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 chain
  • Throws an exception to indicate an error in processing

Other Methods

  • 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.
  • If you wish to pass initialization parameters to the filter you retrieve them from the FilterConfig object passed to init.

Examples

  • This filter records the duration of all requests

import java.io.IOException;
import javax.servlet.http.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; public class TimerFilter implements Filter
{

public void init(FilterConfig arg0) throws ServletException
{
}

public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException
{
long before = System.currentTimeMillis();
chain.doFilter(request, response);
long after = System.currentTimeMillis();
String name = “”;

if (request instanceof HttpServletRequest)
{
name = ((HttpServletRequest)request).getRequestURI();
}

System.out.println(“Time taken to execute “+ name + “is ” + (after – before) +”ms”);
}

public void destroy()
{
}

}

Config

<filter>
<filter-name>timerFilter</filter-name
>
<filter-class>test.TimerFilter</filter-class
>
</filter
>
<filter-mapping
>
<filter-name>timerFilter</filter-name
>
<url-pattern>/*</url-pattern
>
</filter-mapping>

More:

http://www.servlets.com/soapbox/filters.html

http://java.sun.com/products/servlet/Filters.html

Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: