background image

Maintaining Client State

<< Transferring Control to Another Web Component | Associating Objects with a Session >>
<< Transferring Control to Another Web Component | Associating Objects with a Session >>

Maintaining Client State

The web context is used by the Duke's Bookstore filters HitCounterFilter and OrderFilter,
which are discussed in
"Filtering Requests and Responses" on page 114
. Each filter stores a
counter as a context attribute. Recall from
"Controlling Concurrent Access to Shared
Resources" on page 106
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());
...
}
}
Maintaining Client State
Many applications require that a series of requests from a client be associated with one another.
For example, the Duke's Bookstore application saves the state of a user's shopping cart across
requests. Web-based applications are responsible for maintaining such state, called a session,
because HTTP is stateless. To support applications that need to maintain state, Java Servlet
technology provides an API for managing sessions and allows several mechanisms for
implementing sessions.
Accessing a Session
Sessions are represented by an
HttpSession
object. You access a session by calling the
getSession
method of a request object. This method returns the current session associated
with this request, or, if the request does not have a session, it creates one.
Maintaining Client State
Chapter 4 · Java Servlet Technology
125