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();
	}

初级案例,请赐教.

收藏 打印