import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class ShoppingCart extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("
"); if (cart.isEmpty()) out.println("Your shopping cart is empty."); else { out.println("Your shopping cart now contains:
"+ "
| Item | Amount"); Iterator i = cart.entrySet().iterator(); while (i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); out.println(" |
|---|---|
| "+me.getKey()+ " | "+me.getValue()); } out.println(" |
"); out.println("
"); } out.println(""); } void addToCart(Map cart, String item, int amount) { if (amount<0) return; Integer a = (Integer)cart.get(item); if (a==null) a = new Integer(0); cart.put(item, new Integer(a.intValue()+amount)); } }