ava filters, first introduced in the Java Servlet specification 2.3, are a powerful addition to any Java Web application toolkit, yet they probably are the most under-used and under-appreciated of the servlet components. These classes intercept requests coming into and responses coming out of the Java servlet container, allowing developers to inspect and manipulate these messages, as well as take other actions based on the messages' content. Despite this useful functionality, many Java developers are unfamiliar with filters.
What makes filters so powerful is the range of tasks they can perform. For example, you can use them to:
- block non-authenticated users or encrypt sensitive content as it travels back to the client
- compress pages returned from your Web app in order to save bandwidth
- log application access statistics
- transform all your GIF images to PNG images on the fly
Authentication, logging, compression, encryption, transformationfilters can do a lot.
This article demonstrates using filters for Web-application testingspecifically, applying a filter that validates a Web app's HTML against the HTML DTD. The filter uses the W3C's online Markup Validation Service to perform the actual HTML code validation. Since the W3C service can return an XML description of the validation results, you can parse those results and display a formatted list of any issues in the HTML page itself.
You may be wondering: why use a filter when static HTML and public sections of Web apps are so easy to validate? All you need to do is submit the URL to the W3C Validation Service and read the results, right? In fact, browser toolbars and various techniques make this process simple (for example, the W3C site recommends using "favelets" for this purpose). The reason is these techniques do not work for most sophisticated Web apps. Authentication and authorization layers, or using HTTP POSTs eliminate the possibility of submitting simple browser URLs.
Your Java filter gets around these restrictions by buffering the HTTP response, writing it out as a static HTML page, and submitting that static file to the W3C Validation Service. In short, your filter will turn the dynamic request into a static resource and submit that resource, which gets around any security code or other HTTP-related issues.
Validating your Web application's HTML is an important task in its own rightand the subject of more than a few other articles out thereso I won't belabor the point. The numerous reasons for verifying whether your application returns valid HTML include the following:
- Ensuring backwards and forward browser compatibility for your interfaces
- Helping make interface code easier to understand and maintain
- Assisting in correct search-engine parsing and indexing
- Helping make Web pages more accessible