在网上搜了哈关于这个错误的java.util.ConcurrentModificationException信息,
是Collection等,添加Iterator后,在循环内修改是发生的错误。
不知我说的对否?
我这个问题就是:在showcart.jsp页面已经有多个book条目,现在要修改每个book的数量后,update时,就会出现以上信息。
下面是我的代码片段:
显示页面:shwocart.jsp 显示购物车信息
- HTML code
...<% Cart cart = (Cart) session.getAttribute("cart"); if (session.getAttribute("cart") == null) { cart = new Cart(); }%>...<form action="cartAction.jsp?action=update" method="post"><table border="1" width="65%" align="center"> <tr> <td> 编号</td> <td> 书名</td> <td> 作者</td> <td> 数量</td> <td> 单价</td> <td> 总价</td> <td> <a href="cartAction.jsp?action=clear">清空购物车</a> </td> </tr> <% for (Iterator<CartItem> iterator = cart.getItems().iterator(); iterator.hasNext(); ) { CartItem item = (CartItem) iterator.next(); %> <tr> <td> <a href="bookAction.jsp?action=bookdetail&bookId=<%=item.getItem().getBookId()%>"><%=item.getItem().getBookId()%></a> </td> <td> <%=item.getItem().getTitle()%></td> <td> <%=item.getItem().getName()%></td> <!-- 这里文本框名字按bookId命名 --> <td> <input name="<%=item.getItem().getBookId()%>" type="text" value="<%=item.getQuantity()%>" size="4"></td> <td> ¥<%=item.getItem().getPrice()%></td> <td> ¥<%=item.getItemPrice()%></td> <td> <a href="cartAction.jsp?action=remove&bookId=<%=item.getItem().getBookId()%>">删除</a> </td> </tr> <% } %> <tr> <td colspan="6" align="right"> 总计:¥<%=cart.getAmount()%> <br> <input type="submit" value="更新"></td> <td> </td> </tr> <tr> <td colspan="7" align="center"><a href="userAction.jsp?action=pay">付款</a></td> </tr></table></form>...
处理页面:cartAction.jsp 处理购物车所有动作
- HTML code
<%... String action = request.getParameter("action"); String bookId = request.getParameter("bookId"); Cart cart = (Cart)session.getAttribute("cart");... if ("update".equals(action)) { for(Iterator<CartItem> iterator = cart.getItems().iterator(); iterator.hasNext(); ) { CartItem item = (CartItem)iterator.next(); String key = item.getItem().getBookId(); int value = Integer.parseInt(request.getParameter(key)); if(value > 0) { cart.update(key, value); }else{ request.setAttribute("info", "输入数量至少为1"); } } session.setAttribute("cart", cart); pageContext.forward("showcart.jsp"); }...%>
Bean文件:
- Java code
// 该类是Cart(购物车类)里的条目public class CartItem { //BookDetail:图书Bean private BookDetail item; //quantity:该图书条目的数量 private int quantity; public CartItem(BookDetail anItem) { item = anItem; quantity = 1; } public void incrementQuantity() { quantity++; } public BookDetail getItem() { return item; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } //得到该条目的N本书的总价 public double getItemPrice() { return item.getPrice() * quantity; }}