java中集合的取值、遍历及session简单用法

创建Map集合并获取session值:
Map<Integer, Integer> shopCar = (Map<Integer, Integer>) request.getSession().getAttribute(“shopCar”);

// get到shopCar这个map中的所有key
Set ids = shopCar.keySet();

//遍历set中每个key中的值
for (Integer id : ids) {}

//通过每个key(即id),获取该id的每条记录
ProductsEntity products = ProductsEntity.products.get(id);

session简单用法:
// 第一步:先获取session
HttpSession session = request.getSession();
response.setContentType(“text/html;charset=utf-8”);
//将session中的数据赋值map对象
Map<Integer, Integer> shopCar = (Map<Integer, Integer>) session.getAttribute(“shopCar”);
如果为空则:
if (shopCar == null) {
System.out.println("----第一次添加购物车---------------");
// 第三步:如没有,则New一个购物车map对象
shopCar = new HashMap<Integer, Integer>();
// 第四步:将产品id和数量存入购物车map对象中
shopCar.put(Integer.parseInt(id), 1);
} else {
System.out.println("---------再次添加购物车------------");
// 获取map对象中的key
Set ids = shopCar.keySet();
if (ids != null && ids.contains(Integer.parseInt(id))) {
// 如购物车中已存在 此id的产品,则在原基础上数量+1
// 通过map对象中的key,获取map对象中的value
Integer value = shopCar.get(Integer.parseInt(id));
System.out.println(“key:” + id + “,value:” + value);
shopCar.put(Integer.parseInt(id), ++value);
} else {
shopCar.put(Integer.parseInt(id), 1);
}

	}
	session.setAttribute("shopCar", shopCar);
	System.out.println("shopCar:" + shopCar);
	response.setHeader("refresh", "1;url=productList.action");
	PrintWriter pw = response.getWriter();
	pw.println("加入购物车成功,1秒后返回产品列表页");
	pw.flush();
	pw.close();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值