The JavaTM Web Services Tutorial
Home
TOC
Index
PREV TOP NEXT
Divider

Accessing the Web Context

The context in which Web components execute is an object that implements the ServletContext interface. You retrieve the Web context with the getServletContext method. The Web context provides methods for accessing:

The Web context is used by the Duke's Bookstore filters filters.HitCounterFilter and OrderFilter, which were discussed in Filtering Requests and Responses. The filters store a counter as a context attribute. Recall from Controlling Concurrent Access to Shared Resources that the counter's access methods are synchronized to prevent incompatible operations by servlets that are running concurrently. A filter retrieves the counter object with the context's getAttribute method. The incremented value of the counter is recorded with the context's log method.

public final class HitCounterFilter implements Filter {
  private FilterConfig filterConfig = null;
  public void doFilter(ServletRequest request,
    ServletResponse response, FilterChain chain) 
    throws IOException, ServletException {
    ...
    StringWriter sw = new StringWriter();
    PrintWriter writer = new PrintWriter(sw);
    ServletContext context = filterConfig.
      getServletContext();
    Counter counter = (Counter)context.
      getAttribute("hitCounter");
    ...
    writer.println("The number of hits is: " +
      counter.incCounter());
    ...
    context.log(sw.getBuffer().toString());
    ...
  }
}
 
Divider
Home
TOC
Index
PREV TOP NEXT
Divider

This tutorial contains information on the 1.0 version of the Java Web Services Developer Pack.

All of the material in The Java Web Services Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.