Accessing the Web Context

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

  • Initialization parameters

  • Resources associated with the web context

  • Object-valued attributes

  • Logging capabilities

The web context is used by the Duke's Bookstore filters com.sun.bookstore1.filters.HitCounterFilter and OrderFilter, which are discussed in Filtering Requests and Responses (page 77). Each filter stores a counter as a context attribute. Recall from Controlling Concurrent Access to Shared Resources (page 68) that the counter's access methods are synchronized to prevent incompatible operations by servlets that are running concurrently. A filter retrieves the counter object using the context's getAttribute method. The incremented value of the counter is recorded in the log.

   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());        ...        System.out.println(sw.getBuffer().toString());        ...      }    }

The JavaT EE 5 Tutorial
The JavaT EE 5 Tutorial
Year: 2004
Pages: 309 © 2008-2017.
If you may any questions please contact us: