java清空购物车方法_java中的session和cookie实现购物车的结算和清空

只写了一遍的代码:页面的跳转操作,全部是从web文件中读取进行的

web配置文件

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

version="4.0">

demo

com.it.Demo

demo

/CarServlet

demo1

com.it.ClearDemo

demo1

/ClearCartServlet

public class Demo extends HttpServlet {

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

HttpSession session = req.getSession();

resp.setContentType("text/html;charset=utf-8");

int id = Integer.parseInt(req.getParameter("id"));

String[] names = {"iphone7", "小米6", "三星note8", "魅族", "华为9"};

String name = names[id];

// 先拿map对象,如果没有值默认为null

Map cartMap = (Map) session.getAttribute("cart");

// 根据这个对象,判断是否是第一次进来

if (cartMap == null) {

cartMap = new HashMap();

// 如果是第一次进来,就添加一个map对象

session.setAttribute("cart", cartMap);

}

// 判断这个map对象中是否存在手机名称的键

if (cartMap.containsKey(name)) {

cartMap.put(name, cartMap.get(name) + 1);

} else {

cartMap.put(name, 1);

}

System.out.println(cartMap);

resp.getWriter().write("

继续浏览


");

resp.getWriter().write("

去购物车结算


");

}

}

content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

首页

iphone7

小米6

三星note8

魅族

华为9

获取session中的map对象,讲值取出来

Created by IntelliJ IDEA.

User: maotouying

Date: 2019/11/4

Time: 12:53

To change this template use File | Settings | File Templates.

--%>

购物车

您的购物车商品如下:

Map map= (Map)session.getAttribute("cart");

// 遍历map

if (map != null){

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

int value = map.get(key);

%>

名称: 数量:

}

}

%>

清空购物车

清除session中的值,清空购物车

public class ClearDemo extends HttpServlet {

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

HttpSession session = req.getSession();

// 使会话失效

session.invalidate();

resp.sendRedirect("cart.jsp");

}

}


版权声明:本文为weixin_39761481原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。