session实现购物车
程序员文章站
2022-03-15 09:48:51
...
购物车
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
//1.取到商品的对应id
String ids = request.getParameter("id");
int id = Integer.parseInt(ids); //转成int类型
//获取id对应的商品名称
String [] names = {"iphone x","华为p20","三星s9","vivo nex","oppo find x"};
String name = names[id];
//2.获取session里存储的map数据
Map<String,Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cart");
//如果map为空则表明session里没有放数据,则需要创建
if(map==null) {
map =new LinkedHashMap<String,Integer>();
request.getSession().setAttribute("cart", map);
}
//3.如果有则判断是否添加过该商品
if(map.containsKey(name)) {
map.put(name, map.get(name)+1); //有该商品则数量加一
}else {
map.put(name, 1); //没有则添加
}
//4.跳转页面
response.getWriter().write("<a href='product_list.jsp'><h2>继续购物<h2/><a/><br/>");
response.getWriter().write("<a href='cart.jsp'><h2>去购物车结算<h2/><a/><br/>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.removeAttribute("cart");
response.sendRedirect("cart.jsp");
}
上一篇: Cookie
下一篇: C++课程设计之学生成绩管理系统