81,111
社区成员
![](https://csdnimg.cn/release/cmsfe/public/img/topic.427195d5.png)
![](https://csdnimg.cn/release/cmsfe/public/img/me.40a70ab0.png)
![](https://csdnimg.cn/release/cmsfe/public/img/task.87b52881.png)
![](https://csdnimg.cn/release/cmsfe/public/img/share-circle.3e0b7822.png)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
/*使用Map集合实现购物车*/
BookBean bookBean=(BookBean)session.getAttribute("book");
//从session 中得到购物车对象
Map<String,CartItemBean> cartMap=(Map<String,CartItemBean>)session.getAttribute("cartMap");
if(session.getAttribute("cartMap")==null){//如果不存在,则创建一个新的购物车
cartMap=new HashMap<String,CartItemBean>();
session.setAttribute("cartMap", cartMap);
}
//从购物车中获取一个商品对象
CartItemBean cartItemBean=(CartItemBean)cartMap.get(bookBean.getIsbn());
if(cartItemBean==null){//如果为空,则添加一件新的商品
cartMap.put(bookBean.getIsbn(), new CartItemBean(bookBean,1));
}else{//不为空,则更新其数量
cartItemBean.setQuantity(cartItemBean.getQuantity()+1);
}
response.sendRedirect("/Books/viewCart.jsp");
}