java - 为每个循环中的每个对象调用方法时出现 ConcurrentModificationException
问题描述
我目前正在构建一个购物车,我想在结帐后为我的购物车中的每个项目更新我的数据库中的项目库存。
这些项目作为 Java Bean 列表存储在 Session Scope 中。这是我的结帐 servlet。
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final HttpSession session = request.getSession();
@SuppressWarnings("unchecked")
List<CartItems> itemsInWc = (List<CartItems>) session.getAttribute("Cart");
for (CartItems item : itemsInWc) {
updateBestand(item.getInCart(), item.getSize(), item.getId(), item.getKat(), item.getName(), item.getBestand());
}
}
首先,我得到包含项目的列表,然后我遍历eatch 项目并使用“updateBestand”方法更新库存。
public void updateBestand(int inCart, String size, int id, String kategorie, String name, int bestand)
throws ServletException, IOException {
int updateAnzal = bestand - inCart;
try (Connection con = ds.getConnection();
PreparedStatement pstmt = con.prepareStatement("UPDATE " + kategorie + " SET " + size + " =?"
+ " WHERE artikelName = ? and id = ?")) {
pstmt.setInt(1, updateAnzal);
pstmt.setString(2, name);
pstmt.setInt(3, id);
pstmt.executeUpdate();
} catch (Exception ex) {
throw new ServletException(ex.getMessage());
}
}
但是每次我调用我的 checkOut-Servlet 时,它只会更新列表中第一个项目的库存,然后引发 ConcurrentModificationException。
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at Servlets.UpdateBestandServlet.doGet(UpdateBestandServlet.java:40)
解决方案
推荐阅读
- csv - csv 数据错误的分区记录处理器。封装的标记和分隔符之间的字符无效
- javascript - 如何在 Meteor 中将数据从客户端发送到服务器?
- javascript - React Error: Element Type is Invalid with named exports
- flutter - 如何知道用户何时按下返回页面?
- sql - 在 postgreSQL 中使用带有额外列的 GROUP_BY
- crm - GET 请求到 Wiseagent CRM 中的 REST API
- c++ - 当我可以从静态实现相同的目标时,为什么我需要使用动态内存分配?
- elasticsearch - Elasticsearch GET 查询未通过在 GET 调用中提及文档 ID 来返回结果
- javascript - 在 youtube 上添加带有 chrome 扩展名的覆盖按钮
- java - NullPointerException 将对象添加到 ManyToMany Relation Ship 时