<%@ page import="java.util.*" %> Widget Inc.

Widget Inc. Online Shopping

<% Map cart; if (session.isNew()) { cart = new TreeMap(); session.setAttribute("cart", cart); } else cart = (Map)session.getAttribute("cart"); if (request.getMethod().equals("POST")) { String item = request.getParameter("item"); String amount = request.getParameter("amount"); if (item!=null) try { addToCart(cart, item, Integer.parseInt(amount)); } catch (Exception e) { response.sendError(response.SC_BAD_REQUEST, "malformed request"); } } String url = request.getRequestURI(); %>
Item: Amount:

<% if (cart.isEmpty()) { %> Your shopping cart is empty. <% } else { %> Your shopping cart now contains:

ItemAmount <% Iterator i = cart.entrySet().iterator(); while (i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); %>
<%= me.getKey() %> <%= me.getValue() %> <% }%>

">
<% }%> <%! 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)); } %>