1购物车的html页面
<!DOCTYPE html>
<html>
<head>
< charset=\"UTF-8\">
< ></ >
</head>
<body>
<form action=\"Cart\" method=\"post\">
<div>
<ul>
<li>
<input type=\"checkbox\" name=\"cart\" value=\"JAVA编程思想\"/>JAVA编程思想
<input type=\"checkbox\" name=\"cart\" value=\"JAVA核心技术\"/>JAVA核心技术
<input type=\"checkbox\" name=\"cart\" value=\"MYSQL必知必会\"/>MYSQL必知必会
</li>
<input type=\"submit\" value=\"提交\"/>
</ul>
</div>
</form>
</body>
</html>
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<String, Integer> mapcart=(HashMap)session.getAttribute(\"cartMap\");
if(mapcart==null){
//如果时第一次访问则会创建一个Map集合,后面访问直接跳过该验证
mapcart=new HashMap<String, Integer>();
}
//如果用户添加的商品不为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(\"<h1>购物车列表</h1>\");
if(mapcart!=null){
for (String key : mapcart.keySet()) {
out.println(key+mapcart.get(key));
}
}
out.flush();
out.close();
}
初级案例,请赐教.
继续阅读与本文标签相同的文章
上一篇 :
速看!东莞采纳IP王国最新纳入十大知名IP
下一篇 :
携程将在5年内获得全球第一
-
《Android应用开发进阶》| 每日读本书
2026-05-18栏目: 教程
-
“阿里云十年,因为有我而不同”,征文活动开始了!
2026-05-18栏目: 教程
-
玩转 Drone CI
2026-05-18栏目: 教程
-
有关阿里云对SaaS行业的思考,看这一篇就够了
2026-05-18栏目: 教程
-
深入剖析 Delta Lake:详解事务日志
2026-05-18栏目: 教程
