FileDocCategorySizeDatePackage
ShoppingCart.javaAPI DocExample3067Sat Apr 23 22:35:38 BST 2005None

ShoppingCart

public class ShoppingCart extends HttpServlet

Fields Summary
String[]
items
Constructors Summary
Methods Summary
voidaddPurchases(javax.servlet.http.HttpServletRequest request, int[] purchases)

        for (int i=0; i<items.length; i++) {
            String added = request.getParameter( items[i] );
            if ( added !=null && !added.equals("") )
                purchases[i] += Integer.parseInt( added );
        }
    
voiddoForm(java.io.PrintWriter out, java.lang.String requestURI)

        out.println( "<form method=POST action="+ requestURI +">" );

        for(int i=0; i< items.length; i++)
            out.println( "Quantity <input name=\"" + items[i]
              + "\" value=0 size=3> of: " + items[i] + "<br>");
        out.println(
          "<p><input type=submit name=add value=\"Add To Cart\">"
          + "<input type=submit name=checkout value=\"Check Out\">"
          + "<input type=submit name=clear value=\"Clear Cart\">"
          + "</form>" );
    
public voiddoGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)

        response.setContentType("text/html");
        PrintWriter out = response.getWriter(  );

        // get or create the session information
        HttpSession session = request.getSession(  );
        int [] purchases = (int [])session.getAttribute("purchases");
        if ( purchases == null ) {
            purchases = new int [ items.length ];
            session.setAttribute( "purchases", purchases );
        }

        out.println( "<html><head><title>Shopping Cart</title>"
                     + "</title></head><body><p>" );

        if ( request.getParameter("checkout") != null )
            out.println("<h1>Thanks for ordering!</h1>");
        else  {
            if ( request.getParameter("add") != null ) {
                addPurchases( request, purchases );
                out.println(
                    "<h1>Purchase added.  Please continue</h1>");
            } else {
                if ( request.getParameter("clear") != null )
                    for (int i=0; i<purchases.length; i++)
                         purchases[i] = 0;
                out.println("<h1>Please Select Your Items!</h1>");
            }
            doForm( out, request.getRequestURI(  ) );
        }
        showPurchases( out, purchases );
        out.close(  );
    
public voiddoPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)


       
		    
		   
	
        doGet( request, response );
    
voidshowPurchases(java.io.PrintWriter out, int[] purchases)


        out.println("<hr><h2>Your Shopping Basket</h2>");
        for (int i=0; i<items.length; i++)
            if ( purchases[i] != 0 )
                out.println( purchases[i] +"  "+ items[i] +"<br>" );