我有一个问题,如何通过增加数量值而不是在购物车中已经存在的情况下将商品添加到新行中来将其添加到购物车中。
下面是JSP实现MVC的代码
型号
public class Item {
public String id;
public String name;
public double price;
public int quantity;
@Override
public String toString() {
return "Item{" + "id=" + id + ", name=" + name + ", price=" + price + ", quantity=" + quantity + '}';
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public Item(String id, String name, double price, int quantity) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
}
}
控制器
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession mysession = request.getSession();
ArrayList mycart = (ArrayList) mysession.getAttribute("itemlist");
double value = (Double) mysession.getAttribute("total");
String i1 = request.getParameter("item1");
String i2 = request.getParameter("item2");
String delete = request.getParameter("del");
if (i1 != null) {
Item myitem = new Item("1","Kluang Man",3.99,1);
value = value + 3.99;
mycart.add(myitem);
mysession.setAttribute("itemlist", mycart);
mysession.setAttribute("total", value);
response.sendRedirect("cart.jsp");
} else if (i2 != null) {
Item myitem = new Item("2","Usop Santorian",5.99,1);
value = value + 5.99;
mycart.add(myitem);
mysession.setAttribute("itemlist", mycart);
mysession.setAttribute("total", value);
response.sendRedirect("cart.jsp");
} else if (delete != null) {
Item item_to_Delete = (Item) mycart.get(Integer.parseInt(delete));
value = value - item_to_Delete.price;
mysession.setAttribute("total", value);
mycart.remove(Integer.parseInt(delete));
mysession.setAttribute("tod", delete);
response.sendRedirect("cart.jsp");
}
}
查看
<form method="post" action="catalog">
<table class="table table-bordered">
<thead class="thead-light">
<tr align="center">
<th scope="col">Product Name</th>
<th scope="col">Quantity</th>
<th scope="col">Price</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<% if (session.getAttribute("itemlist") != null) {
ArrayList mycart = (ArrayList) session.getAttribute("itemlist");
for (int i = 0; i < mycart.size(); i++) {
Item it = (Item) mycart.get(i);
%>
<tr>
<td align="center"><% out.print(it.name);%></td>
<td align="center"><% out.print(it.quantity);%></td>
<td align="center"><% out.print(it.price);%></td>
<td class="text-center align-middle"><input name="del"
type="submit" value="Remove from cart" class="btn btn-outline-
danger" onclick="this.value=<%out.print(i);%>"></input></td>
</tr>
<%
}
}
%>
<tr>
<td colspan="3" align="right"><h4>Total (RM)</h4></td>
<td align="center"><h4><%= session.getAttribute("total") %></h4></td>
</tr>
</tbody>
</table>
</form>
如果该项目存在,则输出应增加所添加项目的数量,并更新总价值。
答案 0 :(得分:0)
因为您已将myCart定义为ArrayList。 您正在向数组列表添加新对象。
假设列表中的元素属于Item类,则要修改对象,则需要先在列表中找到相应的元素,然后增加其数量。
ArrayList.add()不会修改该对象。它添加了新对象。