jsp电子商务 购物车实现之三 购物车

举报
tea_year 发表于 2021/12/30 00:41:21 2021/12/30
1.9k+ 0 0
【摘要】 CartServlet参考代码 : public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String bookids[] = req.getParameterVa...

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

下面是购物车代码参考:


      <%@ 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>
  
 


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


文章来源: aaaedu.blog.csdn.net,作者:tea_year,版权归原作者所有,如需转载,请联系作者。

原文链接:aaaedu.blog.csdn.net/article/details/53455484

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。