advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Writing Servlet Filters

by Kief Morris kief@kief.com

Filters are an under-appreciated feature of the Java servlet platform, ideal for writing components that can be added transparently to any web application. A filter is like a lightweight servlet that doesn't generate its own content, instead it plugs into the request handling process and executes in addition to the normal page processing.

Filters might record information about requests, convert content to a different format, or even redirect access to a different page. Filters can be applied to any resources served by a servlet engine, whether it's flat HTML, graphics, a JSP page, servlet , or whatever. They can be added to an existing web application without either the filter or the application being aware of one another. Filters are essentially a server plug-in that works with any servlet container compliant with version 2.3 or later of the servlet specification.

A filter implements the interface javax.servlet.Filter, and configured in the web application web.xml file, where the URL's it will process are defined. For each request, the servlet container decides which filters to apply, and adds those filters to a chain in the same order they appear in web.xml. Each filter has its Filter.doFilter() method called, and triggers the invocation of the next filter in the chain or the loading of the final resource (HTML page, servlet, or whatever).

Writing a simple filter

To write a filter, we create a class implementing the Filter interface, which requires three methods: init(), doFilter(), and destroy(). init() and destroy() are called when the filter is first initialized and when it is destroyed, respectively, to allow configuration and cleanup. For the moment we'll ignore these and focus on doFilter(), which is the meat of the filter.

Filter.doFilter()

The servlet container calls the filter's doFilter() method and passes request and response objects for the current request. These are the same objects as a servlet gets, but since there is no HttpFilter, the parameters are defined as javax.servlet.ServletRequest and javax.servlet.ServletResponse, rather than the javax.servlet.http subclasses. This means that if you want to access methods available only on the HTTP versions of the request and response classes, you will need to cast the objects. To be a Good Programmer, you should first test that they actually are the HTTP versions, in case future generations want to use your filter in a non-HTTP servlet environment. Some of the code later in this article shows examples of this.

The third parameter to doFilter() is a FilterChain object, which is used to invoke the next filter in the chain. This is done by calling FilterChain.doFilter() and passing it the request and response objects. If the current filter is the last filter in the chain, the destination resource will be accessed, that is, the HTML page or other static file will be read in, or else a servlet or JSP page will be invoked. After FilterChain.doFilter() returns, the filter can do more processing if it chooses; at this point, the response object should have more fields populated, than it did beforehand, such as the content-type header having been set.

TimerFilter is a simple filter which does nothing more than time how long it takes to process the request after the filter, based directly on the Apache Foundation's Tomcat 4.0 server's ExampleFilter. If this filter is placed as the last filter in the chain, it times the servlet execution or page access itself. Here is the doFilter() method:

public final class TimerFilter implements Filter 
{

    public void doFilter(ServletRequest request, 
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException 
    {

        long startTime = System.currentTimeMillis();
        chain.doFilter(request, response);
        long stopTime = System.currentTimeMillis();
        System.out.println("Time to execute request: " + (stopTime - startTime) + 
            " milliseconds");

    }
...

To compile a Filter you will need to link it with the servlet API classes, which include the interface definitions and other classes used by the filter. These classes are almost certainly available with your servlet container; typically named servlet.jar. If you download the sample source code for this article you can use Ant to compile the code; see the README.txt file for help on configuring the build.

Deploying a filter

To add a filter to a web application, you must first put the compiled filter class in the web application's classpath, which is normally done by putting it under WEB-INF/classes or in a jar file in WEB-INF/lib. The filter is then added to the WEB-INF/web.xml configuration file in much the same way a servlet is, in that there are two configuration blocks. The first defines the filter and gives it a name, and the second defines the circumstances in which the filter is invoked.

The <filter> configuration block

The filter class is defined with a <filter> block, which takes the following child elements:

filter-name The name which will be used to identify the filter elsewhere in the web.xml file.
filter-class The classname, including package, of the filter. This name will be used by the servlet container to load the filter class.
init-param Initialization parameters to pass to the filter. We'll discuss these shortly.
description Long description for the filter, this may be used by configuration tools also.
icon Optional paths to image files for GUI configuration tools to use to represent the filter.
display-name Optional descriptive text for the filter, mainly useful for configuration tools.

The only required elements are the name and class; the icon and display-name are pointless unless you're using a tool which uses them. Here is the configuration for the TimerFilter.

    <filter>
        <filter-name>Timer</filter-name>
        <filter-class>com.kief.FilterDemo.TimerFilter</filter-class>
        <description>
            This filter times the execution of the request after
            the filter itself, and prints the execution time to
            the standard output.
        </description>
    </filter>

Note that the same filter class can be defined in multiple <filter> blocks, each with a different name. This creates a separate instance of the class for each <filter> block, each of which can have different configuration parameters.

 

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Avaya DevConnect Center
 Service Component Architecture/Service Data Objects Solution Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 53
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Cisco Romancing Linux Developers
MobiUI Snares ActionEngine in iPhone/Mobile Push
Windows 7: It's Not Just a Codename Anymore
Microsoft Shines Silverlight on Eclipse
OpenOffice Hits 3.0: Can It Challenge Microsoft?
Get Ready for Microsoft's 'Oslo' Modeling Tool
Latest Linux Hits Networking Flaws
Metasploit 3.2 Offers More 'Evil Deeds'
'Thank You Apple. Seriously.'
The Buzz: BlackBerry App Store Seen Next

Intel Sees Fewer Power Cords in Your Future
F# 101
Use Explicit Conversion Functions to Avert Reckless Implicit Conversions
Polyglot Programming: Building Solutions by Composing Languages
Automated testing for .NET by Ben Hall
"Supply Chain" SOA with SKOS
Service Component Architecture in Real Life
C++Ox: The Dawning of a New Standard
Getting Started with Virtualization
Master Complex Builds with MSBuild

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: BitLocker Encryption on Windows Server 2008
Go Parallel Article: Intel Thread Checker, Meet 20 Million LOC
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Amyuni Download: PDF & XPS Engine for Your .NET and ActiveX Applications
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES