创建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();