FileDocCategorySizeDatePackage
ShoppingCartServlet.javaAPI DocExample3197Sat Mar 15 19:39:50 GMT 2003com.oreilly.javaxp.cactus.servlet

ShoppingCartServlet

public class ShoppingCartServlet extends HttpServlet
author
Brian M. Coyner $version $Id: ShoppingCartServlet.java,v 1.6 2003/02/27 00:24:43 jepc Exp $

Fields Summary
public static final String
INSERT_ITEM
public static final String
REMOVE_ITEM
public static final String
REMOVE_ALL
public static final String
INVALID
public static final String
CART
Constructors Summary
Methods Summary
protected voidaddItemToCart(java.lang.String itemID, ShoppingCart cart)

        Item item = findItem(itemID);
        cart.addItem(item);
    
protected voidclearCart(ShoppingCart cart)

        cart.clear();
    
protected voiddoGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res)


         
               

        HttpSession session = req.getSession(true);
        ShoppingCart cart = (ShoppingCart) session.getAttribute(CART);
        if (cart == null) {
            cart = new ShoppingCart();
            session.setAttribute(CART, cart);
        }
        updateShoppingCart(req, cart);
    
protected ItemfindItem(java.lang.String itemID)

        // this would really need to talk with an EJB to retrieve
        // an Item from a database.  But for this recipe we'll keep
        // it simple.
        return new Item(itemID, "Description " + itemID);
    
protected java.lang.StringgetItemID(javax.servlet.http.HttpServletRequest req)

        String itemID = req.getParameter("itemID");
        if (itemID == null || "".equals(itemID)) {
            return INVALID;
        } else {
            return itemID;
        }
    
protected java.lang.StringgetOperation(javax.servlet.http.HttpServletRequest req)

        String operation = req.getParameter("operation");
        if (operation == null || "".equals(operation)) {
            return INVALID;
        } else {
            if (!INSERT_ITEM.equals(operation)
                    && !REMOVE_ITEM.equals(operation)
                    && !REMOVE_ALL.equals(operation)) {
                return INVALID;
            }

            return operation;
        }
    
protected voidremoveItemFromCart(java.lang.String itemID, ShoppingCart cart)

        cart.removeItem(itemID);
    
protected voidupdateShoppingCart(javax.servlet.http.HttpServletRequest req, ShoppingCart cart)

        String operation = getOperation(req);
        if (INSERT_ITEM.equals(operation)) {
            addItemToCart(getItemID(req), cart);
        } else if (REMOVE_ITEM.equals(operation)) {
            removeItemFromCart(getItemID(req), cart);
        } else if (REMOVE_ALL.equals(operation)) {
            clearCart(cart);
        } else {
            throw new ServletException("Invalid Shopping Cart operation: " +
                                       operation);
        }