购物车关键代码,供自己查阅
/*
* 添加到购物车
* */
public String addToCart(){
//-------------------------------------
Map session = ActionContext.getContext().getSession();
if(session.get("cart")==null){
List<Book> cart = new ArrayList<Book>();
session.put("cart",cart);
}
Book b = bookService.queryById(bookId, false);
b.setBookId(bookId);
// 标记添加的商品是否是同一件商品
boolean same = false;
List<Book> cart = (List<Book>) session.get("cart");
if(cart.size()==0){
b.setCount(b.getCount() + 1);
cart.add(b);
}else{
for (Book bo : cart) {
if(bo.getBookId() == this.getBookId()){
// 购买相同的商品,更新数量
bo.setCount(bo.getCount() + 1);
same = true;
}
}
if(!same){
Book b2 = bookService.queryById(bookId, false);
b2.setCount(b2.getCount() + 1);
cart.add(b2);
}
session.put("cart", cart);
}
return "addToCart_success";
}