10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>The</strong> web context is used by the Duke’s Bookstore filters HitCounterFilter and OrderFilter,<br />

which are discussed in “Filtering Requests and Responses” on page 114. Each filter stores a<br />

counter as a context attribute. Recall from “Controlling Concurrent Access to Shared<br />

Resources” on page 106 that the counter’s access methods are synchronized to prevent<br />

incompatible operations by servlets that are running concurrently. A filter retrieves the counter<br />

object using the context’s getAttribute method. <strong>The</strong> incremented value of the counter is<br />

recorded in the log.<br />

public final class HitCounterFilter implements Filter {<br />

private FilterConfig filterConfig = null;<br />

public void doFilter(ServletRequest request,<br />

ServletResponse response, FilterChain chain)<br />

throws IOException, ServletException {<br />

...<br />

StringWriter sw = new StringWriter();<br />

PrintWriter writer = new PrintWriter(sw);<br />

ServletContext context = filterConfig.<br />

getServletContext();<br />

Counter counter = (Counter)context.<br />

getAttribute("hitCounter");<br />

...<br />

writer.println("<strong>The</strong> number of hits is: " +<br />

counter.incCounter());<br />

...<br />

System.out.println(sw.getBuffer().toString());<br />

...<br />

}<br />

}<br />

Maintaining Client State<br />

Many applications require that a series of requests from a client be associated with one another.<br />

For example, the Duke’s Bookstore application saves the state of a user’s shopping cart across<br />

requests. Web-based applications are responsible for maintaining such state, called a session,<br />

because HTTP is stateless. To support applications that need to maintain state, <strong>Java</strong> Servlet<br />

technology provides an API for managing sessions and allows several mechanisms for<br />

implementing sessions.<br />

Accessing a Session<br />

Maintaining Client State<br />

Sessions are represented by an HttpSession object. You access a session by calling the<br />

getSession method of a request object. This method returns the current session associated<br />

with this request, or, if the request does not have a session, it creates one.<br />

Chapter 4 • <strong>Java</strong> ServletTechnology 125

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!