JavaWeb基础(购物车案例实现Session)

本文介绍了使用JavaWeb的Session来实现购物车功能的初级案例,包括购物车的HTML页面设计和Servlet页面的处理逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1购物车的html页面

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</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();
	}

初级案例,请赐教.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值