繁体   English   中英

通过Servlet使用会话将多个商品添加到购物车

[英]adding multiple items to shopping cart using session through servlet

我想使用session.i添加多个项目以将其添加到购物车中。我编写代码仅是为了向购物车中添加一个项目。 您能建议我如何添加多个项目吗?

String name=req.getParameter("n");
        String cost=req.getParameter("c");

        HttpSession s=req.getSession();
        s.setAttribute("name",name);
        s.setAttribute("cost",cost);
        out.println("item successfully added to cart");
        out.println("\n<a href=\'viewserv\'>view cart</a>");

您应该使用List添加多个购物车。 要存储名称和成本,请使用具有这些属性的模型类Cart

class Cart{
   String name;
   double cost;
  // Getter & Setter

}

现在,将多个购物车值添加到List 这是示例代码片段。

  String name=req.getParameter("n");
  String cost=req.getParameter("c");

  HttpSession s=req.getSession();

  List<Cart> list= (List<Cart>) s.getAttribute("list");

  if(list==null){
    list =new ArrayList<>();
  }
  // Add the name & cost to List
  list.add(new Cart(name, cost));

  s.setAttribute("list",list);

编辑:

要显示列表值,您需要迭代列表

 for(Cart cart : list){
   out.println("Name "+ cart.getName());
   out.println("Cost "+ cart.getCost());
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM