更新ArrayList中已经存在的元素



我正在使用jsp和servlet创建一个工作购物车,用户可以在其中添加和删除购物车中的商品。这些物品将被陈列在一张桌子上。对于这些特性,代码工作得很好,除了一个bug,当添加具有相同ID的项目时,它只是添加一个新行,而不是更新现有的记录.

结果:

|    Item ID    |     Item Name    |         Qty      |      Action      |
|---------------|------------------|------------------|------------------|
|       1       |        Bag       |         1        |    Remove Item   |
|       2       |     Pencil       |         5        |    Remove Item   |
|       1       |        Bag       |         3        |    Remove Item   |

预期结果:

|    Item ID    |     Item Name    |         Qty      |      Action      |
|---------------|------------------|------------------|------------------|
|       1       |        Bag       |         4        |    Remove Item   |
|       2       |     Pencil       |         5        |    Remove Item   |

JSP:index.jsp

<body>
<h1>Cart</h1>
<form action="addToCart" method="POST">
<input type="text" name="id" placeholder="Item ID"/><br>
<input type="text" name="itemName" placeholder="Item Name"/><br>
<input type="text" name="qty" placeholder="Qty"/><br>
<input type="submit" name="submit" value="Add"/><br>
</form>

<table>
<th>Item ID</th>
<th>Item Name</th>
<th>Qty</th>
<th>Action</th>

<% 
ArrayList<Item> arrayList = new ArrayList<Item>();
if (request.getServletContext().getAttribute("cartItemList") != null) {
arrayList = (ArrayList<Item>) request.getServletContext().getAttribute("cartItemList");

if(!arrayList.isEmpty()) 
{
for (Item item : arrayList)
{
%>

<tr>
<td><%= item.getItemId() %></td>
<td><%= item.getItemName() %></td>
<td><%= item.getQty() %></td>
<td><form method="POST" action="removeFromCart">
<input type="text" name="id" value="<%= item.getItemId() %>" hidden/>
<input type="submit" name="remove" value="Remove Item">
</form>
</td>
</tr>
<% 
}       
}
}
%>
</table>
</body>l>

控制器(Servlet doPost方法):addToCart.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();
processRequest(request, response);   
request.getSession();
String id = request.getParameter("id");
String itemName = request.getParameter("itemName");
String qty = request.getParameter("qty");
Item item = new Item();
item.setItemId(id);
item.setItemName(itemName);
item.setQty(Integer.parseInt(qty));

ArrayList<Item> arrayList = new ArrayList<Item>();
request.getSession().setAttribute("array", arrayList);
arrayList.add(item);
if(request.getServletContext().getAttribute("cartItemList")  != null) 
{
// attempt to UPDATE Quantity if the same item was previously added
if (arrayList.contains(id)) // if arrayList already contains the same id entered by user
{
Iterator<Item> it = arrayList.iterator();
//iterate through datas
int ctr = 0;
int total = item.getQty();
while (it.hasNext()) 
{
Item name = it.next();
//check if values matches
if (name.getItemId().equals(id)) 
{
total += name.getQty(); // add the new quantity to the existing one
}
else 
{
ctr++; 
}
}
arrayList = (ArrayList<Item>) request.getServletContext().getAttribute("cartItemList");

item = arrayList.get(ctr); // get the item at the index it was found
item.setQty(total); // set the quantity to the sum of the old quantoty and new quantity entered by user

//pass updated value to jsp page
request.getSession().setAttribute("cartItemList", arrayList);
request.getRequestDispatcher("index.jsp").forward(request, response);
request.getSession().setAttribute("cartItemList", arrayList);
} 
else if (!arrayList.contains(id)) // if arrayList does not contain the same id entered by user
{
arrayList = (ArrayList<Item>) request.getServletContext().getAttribute("cartItemList");
arrayList.add(item);
request.getServletContext().setAttribute("cartItemList", arrayList);
}
}
else
{
request.getServletContext().setAttribute("cartItemList", arrayList); 
} 

response.sendRedirect("index.jsp");
}
型号:Item.java
public class Item {
private String itemId;
private String itemName;
private int qty;
private String submit;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}

我在addToCart.java中标记了我试图创建用于更新其新数量的特定行的代码的部分。我只是不知道我应该放置什么代码,以便它更新现有的数量,而不是创建一个新的行。提前感谢您的帮助!

arrayList.contains(id)由于对象的原因永远不会相同。你必须在Item类中实现equalshashcode

public class Item {
private String itemId;
private String itemName;
private int qty;
private String submit;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
@Override
public int hashCode() {
return Objects.hash(itemId);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Item)) {
return false;
}
Item other = (Item) obj;
return Objects.equals(itemId, other.itemId);
}
}

上面的代码检查itemId是否相同,则认为对象相同,尽管数量不同。

。查找现有项目和更新的逻辑似乎是错误的。如果条目匹配,则需要中断for循环。更新addToCart.java.

中的代码
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
processRequest(request, response);
request.getSession();
String id = request.getParameter("id");
String itemName = request.getParameter("itemName");
String qty = request.getParameter("qty");
Item item = new Item();
item.setItemId(id);
item.setItemName(itemName);
item.setQty(Integer.parseInt(qty));
ArrayList<Item> arrayList = new ArrayList<>();
if (request.getServletContext().getAttribute("cartItemList") != null) {
arrayList = (ArrayList<Item>) request.getServletContext().getAttribute("cartItemList");
// attempt to UPDATE Quantity if the same item was previously added
if (arrayList.contains(item)) {
Item existingItem = arrayList.get(arrayList.indexOf(item));
existingItem.setQty(existingItem.getQty() + item.getQty());
// pass updated value to jsp page
request.getSession().setAttribute("cartItemList", arrayList);
request.getRequestDispatcher("index.jsp").forward(request, response);
request.getSession().setAttribute("cartItemList", arrayList);
} else {
arrayList.add(item);
request.getServletContext().setAttribute("cartItemList", arrayList);
}
} else {
arrayList.add(item);
request.getServletContext().setAttribute("cartItemList", arrayList);
}
response.sendRedirect("index.jsp");
}

更多细节https://initialcommit.com/blog/working-hashcode-equals-java

相关内容

  • 没有找到相关文章

最新更新