import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;

// This is a very simple servlet that keeps reads the "shopping cart" 
// created for each user in a HttpSession object.

public class PurchaseServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response) 
                    throws ServletException, IOException {
 
    PrintWriter out = response.getWriter();

    // Get the item and quantities entered

    // Get the seesion object associated with this user (or create a new 
    // one if none exists)

    HttpSession session = request.getSession();

    // We can use the session to determine whether the user has
    // skipped required stages to reach this point (possibly by
    // typing in the URL to this point) by checking session
    // attibutes which are set by previous required stages.

    if (session.getAttribute("itemPurchased") == null) {
      RequestDispatcher noPurchase = 
         request.getRequestDispatcher("Form");
      noPurchase.forward(request, response);
      return;
      }

    out.println("<HTML><BODY><H3>You have purchased:</H3>");
    out.println("<TABLE><TR><TD>Item</TD><TD>Quantity</TD></TR>");

    Enumeration allItemNames = session.getAttributeNames();

    while (allItemNames.hasMoreElements()) {
      String itemName = (String)allItemNames.nextElement();
      String itemQuantity = (String)session.getAttribute(itemName);
     if (!itemName.equals("itemPurchased"))
        out.println("<TR><TD>" + itemName + "</TD><TD>" + itemQuantity + "</TD></TR>");
      }
    out.println("</TABLE>");

    // We can also use the session Id as a purchase order number.
    // The response.encodeURL adds the session ID to the path if
    // cookies cannot be used.

    out.println("<BR>Your order number is " + session.getId());
    out.println("</P></BODY></HTML>");

    }
  }
