Maintaining Client State - The Java EE 5 Tutorial (original) (raw)
2. Using the Tutorial Examples
3. Getting Started with Web Applications
Troubleshooting Duke's Bookstore Database Problems
Handling Servlet Life-Cycle Events
Specifying Event Listener Classes
Controlling Concurrent Access to Shared Resources
Getting Information from Requests
Filtering Requests and Responses
Programming Customized Requests and Responses
Including Other Resources in the Response
Transferring Control to Another Web Component
Notifying Methods to Shut Down
Creating Polite Long-Running Methods
Further Information about Java Servlet Technology
5. JavaServer Pages Technology
7. JavaServer Pages Standard Tag Library
10. JavaServer Faces Technology
11. Using JavaServer Faces Technology in JSP Pages
12. Developing with JavaServer Faces Technology
13. Creating Custom UI Components
14. Configuring JavaServer Faces Applications
15. Internationalizing and Localizing Web Applications
16. Building Web Services with JAX-WS
17. Binding between XML Schema and Java Classes
19. SOAP with Attachments API for Java
21. Getting Started with Enterprise Beans
23. A Message-Driven Bean Example
24. Introduction to the Java Persistence API
25. Persistence in the Web Tier
26. Persistence in the EJB Tier
27. The Java Persistence Query Language
28. Introduction to Security in the Java EE Platform
29. Securing Java EE Applications
31. The Java Message Service API
32. Java EE Examples Using the JMS API
36. The Coffee Break Application
37. The Duke's Bank Application
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.
Associating Objects with a Session
You can associate object-valued attributes with a session by name. Such attributes are accessible by any web component that belongs to the same web context andis handling a request that is part of the same session.
The Duke’s Bookstore application stores a customer’s shopping cart as a session attribute. This allows the shopping cart to be saved between requests and also allows cooperating servlets to access the cart. CatalogServlet adds items to the cart;ShowCartServlet displays, deletes items from, and clears the cart; and CashierServlet retrieves the total cost of the books in the cart.
public class CashierServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get the user’s session and shopping cart
HttpSession session = request.getSession();
ShoppingCart cart =
(ShoppingCart)session.
getAttribute("cart");
...
// Determine the total price of the user’s books
double total = cart.getTotal();
Notifying Objects That Are Associated with a Session
Recall that your application can notify web context and session listener objects of servlet life-cycle events (Handling Servlet Life-Cycle Events). You can also notify objects of certain events related to their association with a session such as the following:
- When the object is added to or removed from a session. To receive this notification, your object must implement the javax.servlet.http.HttpSessionBindingListener interface.
- When the session to which the object is attached will be passivated or activated. A session will be passivated or activated when it is moved between virtual machines or saved to and restored from persistent storage. To receive this notification, your object must implement the javax.servlet.http.HttpSessionActivationListener interface.
Session Management
Because there is no way for an HTTP client to signal that it no longer needs a session, each session has an associated timeout so that its resources can be reclaimed. The timeout period can be accessed by using a session’s [get|set]MaxInactiveInterval methods.
You can also set the timeout period in the deployment descriptor using NetBeans IDE:
- Open the web.xml file in the web.xml editor.
- Click General at the top of the editor.
- Enter an integer value in the Session Timeout field. The integer value represents the number of minutes of inactivity that must pass before the session times out.
To ensure that an active session is not timed out, you should periodically access the session by using service methods because this resets the session’s time-to-live counter.
When a particular client interaction is finished, you use the session’s invalidate method to invalidate a session on the server side and remove any session data. The bookstore application’s ReceiptServlet is the last servlet to access a client’s session, so it has the responsibility to invalidate the session:
public class ReceiptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user’s session and shopping cart HttpSession session = request.getSession(); // Payment received -- invalidate the session session.invalidate(); ...
Session Tracking
A web container can use several methods to associate a session with a user, all of which involve passing an identifier between the client and the server. The identifier can be maintained on the client as a cookie, or the web component can include the identifier in every URL that is returned to the client.
If your application uses session objects, you must ensure that session tracking is enabled by having the application rewrite URLs whenever the client turns off cookies. You do this by calling the response’s encodeURL(URL) method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged.
The doGet method of ShowCartServlet encodes the three URLs at the bottom of the shopping cart display page as follows:
out.println("
<a href="" + response.encodeURL(request.getContextPath() + "/bookcatalog") + "">" + messages.getString("ContinueShopping") + " " + "<a href="" + response.encodeURL(request.getContextPath() + "/bookcashier") + "">" + messages.getString("Checkout") + " " + "<a href="" + response.encodeURL(request.getContextPath() + "/bookshowcart?Clear=clear") + "">" + messages.getString("ClearCart") + "");
If cookies are turned off, the session is encoded in the Check Out URL as follows:
http://localhost:8080/bookstore1/cashier;jsessionid=c0o7fszeb1
If cookies are turned on, the URL is simply
http://localhost:8080/bookstore1/cashier
Copyright © 2010, Oracle and/or its affiliates. All rights reserved. Legal Notices