欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jsp电子商务 购物车实现之 购物车和结算篇

程序员文章站 2024-03-20 14:16:46
...

CartServlet参考代码 :

public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String bookids[] = req.getParameterValues("bookId"); //id数组;
		
		Map<Integer,Book> cart = (Map<Integer,Book>)req.getSession().getAttribute("cart");
		//System.out.println(cart.size()); null对
		/*
		 *     Integer   Book
		 *     id        book  (count)       
		 *     7         book  (count=2)
		 *     8         book  ( count=5)
		 * 
		 * */
		
		BookDao bd = new BookDaoImpl();
		//如果购物车为null,则new出来一个HashMap对象
		if(cart==null){
			cart = new HashMap<Integer,Book>();//id以及book对象
			req.getSession().setAttribute("cart", cart);
		}
		
		for(String bookid:bookids){
			Book book = cart.get(Integer.parseInt(bookid));
			if(book==null){
				book = bd.findById(Integer.parseInt(bookid));//根据id获得书籍
				book.setCount(1);//数量为1
			}
			else{
				// 判断是否已经是最后一本书;数量大于获得数量,其他的不能再加数量了
				if(book.getStock()>book.getCount()){
					book.setCount(book.getCount()+1);
				}
			}
			cart.put(Integer.parseInt(bookid), book);
			//需要放入到数据库中,那么购物车表的字段是什么呢?
			//图书id 书名  图片名 数量 合计价格
		}
		
		req.getSession().setAttribute("cart", cart);
		resp.sendRedirect("cart.jsp");
	}

在该Servlet中利用了session进行存放值,就是开篇我们的方法之一,但是这种方法有什么问题呢?大家好好思考下!!!

下面是购物车代码参考:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'cart.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	
  <link rel="stylesheet" href="css/style.css" type="text/css"></link>
  
  <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
  
  <script type="text/javascript">
  	function jian(id){
		if($("#count"+id).val()==1){
		//采用淘宝模式,如果低于1,则不用提示,直接不可用;
			$("#count"+id).prev().attribute("disabled","disabled");
			return;
		}
  	
  		$.ajax({
  			url:'ChangeCartCountServlet',
  			type:'post',
  			dataType:'text',
  			data:{
  				bookid:id,
  				count:parseInt($("#count"+id).val())-1   //  -1
  			},
  			success:function(data){
  				
 				var price = $("#price"+id).html();
		  		$("#count"+id).val(parseInt($("#count"+id).val())-1);
		  		$("#sum"+id).val("¥"+price*$("#count"+id).val());
		  		
		  		calcTotal();
  				
  			}
  		});
  	}
  	
  	function add(id){
  		$.ajax({
  			url:'ChangeCartCountServlet',
  			type:'post',
  			dataType:'text',
  			data:{
  				bookid:id,
  				count:parseInt($("#count"+id).val())+1
  			},
  			success:function(data){
  				if(data=="false"){
  					alert("库存不足!!!!");				
  				}
  				else{
  					var price = $("#price"+id).html();
			  		$("#count"+id).val(parseInt($("#count"+id).val())+1);
			  		$("#sum"+id).val("¥"+price*$("#count"+id).val());
			  		
			  		calcTotal();
  				}
  			}
  		});
  	
  	
  		
  		
  	}
  	
  	function calcTotal(){
  		// input...
  		var counts = $("input[id^=count]").toArray();  
  		var prices = $("div[id^=price]").toArray();
  		var total = 0;
  		
  		for(var i=0;i<prices.length;i++){
  			total += prices[i].innerHTML*counts[i].value;
  		}
  		
  		$("#total").val("¥"+total);
  	}
  
  </script>
  
  </head>
  
  <body>
   <div id="header" class="wrap">
	<div id="banner"></div>
	<div id="navbar">
		<div class="userMenu">
			<ul>
				<li class="current"><font color="BLACK">欢迎您,<strong>andy</strong></font>   </li>
				<li><a href="index.html">首页</a></li>
				<li><a href="orderlist.html">我的订单</a></li>
				<li><a href="cart.html">购物车</a></li>
				<li><a href="logout.jsp">注销</a></li>
			</ul>
		</div>
	</div>
</div>
<div id="content" class="wrap">
	<div class="list bookList">
		<form method="post" name="shoping" action="BuyServlet">
			<table>
				<tr class="title">
					<th class="view">图片预览</th>
					<th>书名</th>
					<th class="nums">数量</th>
					<th class="price">价格</th>
					<th class="nums">合计</th>
					<th class="nums">操作</th>
				</tr>
					
					<c:set var="total" value="0"></c:set>
					
					<c:forEach items="${cart}" var="book">	
					<tr>
						
						<td class="thumb">
						<img src="images/book/${book.value.image}" /></td>
						<td class="title">${book.value.bookname}</td>
						<td>
						<img src="images/edit_jian.png" width="12" height="12" 
							οnclick="jian(${book.value.id})"/>
							
						<input id="count${book.value.id}" readonly="readonly"
							value="${book.value.count}" size="2"/>
							
						<img src="images/edit_add.png" width="12" height="12" 
						    οnclick="add(${book.value.id})"/>
						</td>
						
						<td>¥
							<div id="price${book.value.id}" >${book.value.price}</div>
						</td>
						<td>
							<input id="sum${book.value.id}"
							value='<fmt:formatNumber 
								value="${book.value.count*book.value.price}"
								type="currency"></fmt:formatNumber>'
							/>
							
							
							<c:set var="total" 
								value=
								"${total+book.value.count*book.value.price}"></c:set>
							
							<input type="hidden" name="items" value="10:2:31.6"/>
						</td>
						<td>
						<a href="DeleteCartItemServlet?bookid=${book.value.id}">删除</a>
						</td>
					</tr>
					</c:forEach>
				
				<tr>
					<td>
						地址
					</td>
					<td colspan="5">
						<input name="shipaddress">
					</td>
				</tr>
				<tr>
					<td>
						电话
					</td>
					<td colspan="5">
						<input name="contactphone">
					</td>
				</tr>	
				<tr><td colspan="5">
				
			<div class="button">
				<h4>总价:
					<input id="total" 
						value='<fmt:formatNumber value="${total}" type="currency"></fmt:formatNumber>'
					/>
				元</h4>
				<input type="hidden" id="hidden_total_price" name="hidden_total_price"/>
				<input class="input-chart" type="submit" name="submit" value="" />
			</div>
			</td></tr>
				
			</table>
		</form>
	</div>
</div>
</body>
	<div id="footer" class="wrap">
		网上书城 &copy; 版权所有
	</div>
</html>
 


</html>
根据id从购物车中删除的Servlet代码参考如下:

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		int bookid = Integer.parseInt(req.getParameter("bookid"));
				
				Map<Integer,Book> cart = (Map<Integer,Book>)
					req.getSession().getAttribute("cart");
				// 根据key(bookid)删除
				cart.remove(bookid);
				
				req.getSession().setAttribute("cart", cart);
				
				resp.sendRedirect("cart.jsp");
	}


上一篇: C初级_顺序表

下一篇: 购物车功能