Sunday, October 17, 2010

Observing HttpServletResponses

Motivation

Filters are a great way to observe (or even modify) the response generated for an HTTP request. This post will present a handy application of the observer pattern from within a Java web Filter, allowing developers to monitor responses to HTTP requests as they are constructed.

Implementation

The response observer filter I want to describe is part of Big-Oh Software's CommonWeb Framework. That framework defines a ResponseObserver interface that models the events that transpire while constructing the response to an HTTP request. A simple, abstract filter class, ResponseObserverFilter, serves as the base class for (potentially) many filters that observe those events.

An Example: Response Size Monitor Filter

Because the abstract ResponseObserverFilter utilizes the observer pattern, we can use it to define many useful, concrete filters without having to write much code. For example, it is quite easy to create a ResponseSizeMonitorFilter that announces the size of the response generated for an HTTP request.

Applying the ResponseSizeMonitorFilter to the servlets in your web application is a simple matter of including the snippet below in your web.xml file:

<!-- web.xml snippet -->

<filter>
  <filter-name>ResponseSizeMonitorFilter</filter-name>
  <filter-class>net.big_oh.common.web.impl.ResponseSizeMonitorFilter</filter-class>
</filter>

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

The ResponseSizeMonitorFilter will now log the size of HTTP responses in the following format:
The response for the requested url (http://127.0.0.1:8080/CommonWeb/ImageServlet) contained about 4.09 kilobytes.

No comments:

Post a Comment