Home TOC |
Search
Feedback |
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:
- Initialization parameters
- Resources associated with the web context
- Object-valued attributes
- Logging capabilities
The web context is used by the Duke's Bookstore filters filters.HitCounterFilter and OrderFilter discussed in Filtering Requests and Responses. The filters store a counter (util.Counter) as a context attribute. 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()); ... } } public class Counter { private int counter; public Counter() { counter = 0; } public synchronized int getCounter() { return counter; } public synchronized int incCounter() { return(counter++); } }
Home TOC |
Search
Feedback |