Chapter 4. Session Management

Write servlet code to store objects into a session object and retrieve objects from a session object.

Sessions are represented by an HttpSession object. You access a session by calling the HttpServletRequest.getSession() or HttpServletRequest.getSession(boolean) 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 (unless boolean argument is false).

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 and is handling a request that is part of the same session.

For example, you can save 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. Some servlet adds items to the cart; another servlet displays, deletes items from, and clears the cart; and next servlet retrieves the total cost of the items in the cart.

public class CashierServlet extends HttpServlet {
	public void doGet (HttpServletRequest req, HttpServletResponse res)
			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(); 

package javax.servlet.http;

public interface HttpSession {

	public java.lang.Object getAttribute(java.lang.String name);
	public java.util.Enumeration getAttributeNames();
	public void removeAttribute(java.lang.String name);
	public void setAttribute(java.lang.String name, java.lang.Object value);


Professional hosting     Belorussian informational portal         Free SCBCD 1.3 Study Guide     Free SCDJWS 1.4 Study Guide     SCDJWS 1.4 Quiz     Free IBM Certified Associate Developer Study Guide     Free SCJP 5.0 (Tiger) Study Guide     Free Mock Exam Engine     IBM Test 000-287. Enterprise Application Development with IBM WebSphere Studio, V5.0 Study Guide