Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Servlet 2.3: New features exposed

A full update on the latest Servlet API spec

  • Print
  • Feedback

Page 2 of 5

The Servlet API 2.3 is slated to become a core part of Java 2 Platform, Enterprise Edition 1.3 (J2EE 1.3). The previous version, Servlet API 2.2, was part of J2EE 1.2. The only noticeable difference is the addition of a few relatively obscure J2EE-related deployment descriptor tags in the web.xml DTD: <resource-env-ref> to support "administered objects," such as those required by the Java Messaging System (JMS); <res-ref-sharing-scope> to allow either shared or exclusive access to a resource reference; and <run-as> to specify the security identity of a caller to an EJB. Most servlet authors need not concern themselves with those J2EE tags; you can get a full description from the J2EE 1.3 specification.

Filters

The most significant part of API 2.3 is the addition of filters -- objects that can transform a request or modify a response. Filters are not servlets; they do not actually create a response. They are preprocessors of the request before it reaches a servlet, and/or postprocessors of the response leaving a servlet. In a sense, filters are a mature version of the old "servlet chaining" concept. A filter can:

  • Intercept a servlet's invocation before the servlet is called
  • Examine a request before a servlet is called
  • Modify the request headers and request data by providing a customized version of the request object that wraps the real request
  • Modify the response headers and response data by providing a customized version of the response object that wraps the real response
  • Intercept a servlet's invocation after the servlet is called


You can configure a filter to act on a servlet or group of servlets; that servlet or group can be filtered by zero or more filters. Practical filter ideas include authentication filters, logging and auditing filters, image conversion filters, data compression filters, encryption filters, tokenizing filters, filters that trigger resource access events, XSLT filters that transform XML content, or MIME-type chain filters (just like servlet chaining).

A filter implements javax.servlet.Filter and defines its three methods:

  • void setFilterConfig(FilterConfig config): Sets the filter's configuration object
  • FilterConfig getFilterConfig(): Returns the filter's configuration object
  • void doFilter(ServletRequest req, ServletResponse res, FilterChain chain): Performs the actual filtering work


The server calls setFilterConfig() once to prepare the filter for service, then calls doFilter() any number of times for various requests. The FilterConfig interface has methods to retrieve the filter's name, its init parameters, and the active servlet context. The server passes null to setFilterConfig() to indicate that the filter is being taken out of service.

Each filter receives in its doFilter() method 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. (It could gather data by calling their methods, or wrap the objects to give them new behavior, as discussed below.) 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.

A filter may wrap the request and/or response objects to provide custom behavior, changing certain method call implementation to influence later request handling actions. API 2.3 provides new HttpServletRequestWrapper and HttpServletResponseWrapper classes to help with this; they provide default implementations of all request and response methods, and delegate the calls to the original request or response by default. That means changing one method's behavior requires just extending the wrapper and reimplementing one method. Wrappers give filters great control over the request-handling and response-generating process. The code for a simple logging filter that records the duration of all requests is shown below:

public class LogFilter implements Filter {
  FilterConfig config;
  public void setFilterConfig(FilterConfig config) {
    this.config = config;
  }
  public FilterConfig getFilterConfig() {
    return config;
  }
  public void doFilter(ServletRequest req,
                       ServletResponse res,
                       FilterChain chain) {
    ServletContext context = getFilterConfig().getServletContext();
    long bef = System.currentTimeMillis();
    chain.doFilter(req, res);  // no chain parameter needed here
    long aft = System.currentTimeMillis();
    context.log("Request to " + req.getRequestURI() + ": " + (aft-bef));
  }
}


When the server calls setFilterConfig(), the filter saves a reference to the config in its config variable, which is later used in the doFilter() method to retrieve the ServletContext. The logic in doFilter() is simple; time how long request handling takes and log the time once processing has completed. To use this filter, you must declare it in the web.xml deployment descriptor using the <filter> tag, as shown below:

<filter>
  <filter-name>
    log
  </filter-name>
  <filter-class>
    LogFilter
  </filter-class>
</filter>


This tells the server a filter named log is implemented in the LogFilter class. You can apply a registered filter to certain URL patterns or servlet names using the <filter-mapping> tag:

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


This configures the filter to operate on all requests to the server (static or dynamic), just what we want for our logging filter. If you connect to a simple page, the log output might look like this:

Request to /index.jsp: 10


Lifecycle events

Servlet API 2.3's second most significant change is the addition of application lifecycle events, which let "listener" objects be notified when servlet contexts and sessions are initialized and destroyed, as well as when attributes are added or removed from a context or session.

Servlet lifecycle events work like Swing events. Any listener interested in observing the ServletContext lifecycle can implement the ServletContextListener interface. The interface has two methods:

  • void contextInitialized(ServletContextEvent e): Called when a Web application is first ready to process requests (i.e. on Web server startup and when a context is added or reloaded). Requests will not be handled until this method returns.
  • void contextDestroyed(ServletContextEvent e): Called when a Web application is about to be shut down (i.e. on Web server shutdown or when a context is removed or reloaded). Request handling will be stopped before this method is called.


The ServletContextEvent class passed to those methods has only a getServletContext() method that returns the context being initialized or destroyed.

  • Print
  • Feedback

Resources