java购物车session实现_JavaWeb基础(购物车案例实现Session)

1购物车的html页面

  • JAVA编程思想

    JAVA核心技术

    MYSQL必知必会

2购物车的Servlet页面

public class ShoppingCart extends HttpServlet {

//实例化购物车实体类集合

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//解决编码问题

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

//获得session

HttpSession session=request.getSession();

//获得用户选择的购物车内容

String [] books=request.getParameterValues("cart");

//获得购物车列表,如果时第一次访问,则为Null

HashMap mapcart=(HashMap)session.getAttribute("cartMap");

if(mapcart==null){

//如果时第一次访问则会创建一个Map集合,后面访问直接跳过该验证

mapcart=new HashMap();

}

//如果用户添加的商品不为null,则向里里面添加商品;

if(books!=null){

//遍历,得出用户所选的所有商品

for (int i = 0; i < books.length; i++) {

//判断,用户所选的商品是否已经存在

if(mapcart.containsKey(books[i])){

//如果已经存在,则直接添加,获得其已存在的商品数量,并增加1mapcart.get(books[i])+1

mapcart.put(books[i],mapcart.get(books[i])+1);

}else{

//如果不存在,则直接添加,数量为1

mapcart.put(books[i],1);

}

}

}

session.setAttribute("cartMap", mapcart);

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.print("

购物车列表

");

if(mapcart!=null){

for (String key : mapcart.keySet()) {

out.println(key+mapcart.get(key));

}

}

out.flush();

out.close();

}

初级案例,请赐教.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值