import java.util.Vector; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Shop extends HttpServlet { Vector inventory = new Vector(); Cart cart; public Shop() { inventory.add(new Item(0, "Thinkpad", 1200.00)); inventory.add(new Item(1, "Printer", 124.99)); inventory.add(new Item(2, "D-RAM", 88.99)); } public void checkout(PrintWriter out) { out.println("You have: " + cart.showCart + " things"); } public void addItems(HttpServletRequest request, PrintWriter out) { String[] id = request.getParameterValues("id"); if (id == null) out.println("received nothing

"); else { for (int i = 0; i < id.length; i++) cart.add(Integer.parseInt(id[i])); } out.println("Your cart: " + cart.showCart()); out.println("Back to list "); out.println("Check out to checkout "); out.println("Clear your cart"); } public void showItems(PrintWriter out) { out.println("List of available items
"); out.println("

"); out.println(""); for (int i = 0; i < inventory.size(); i++) { Item item = (Item)inventory.get(i); out.println(""); out.println("Name: " + item.name + " for $" + item.price + "
"); } out.println(""); out.println("
"); } public void invalidCommand(PrintWriter out) { out.println("

Invalid command

"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); cart = (Cart)session.getAttribute("shu.cart"); if (cart == null) { cart = new Cart(); session.setAttribute("shu.cart", cart); } out.println(""); out.println("

Magical Mystery Shopping Machine

"); String cmd = request.getParameter("cmd"); if (cmd == null) cmd = "show"; if (cmd.equals("show")) showItems(out); else if (cmd.equals("add")) addItems(request, out); else if (cmd.equals("checkout")) checkout(out); else invalidCommand(out); out.println(""); out.close(); } }