前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >jsp电子商务 购物车实现之三 购物车

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

作者头像
用户9184480
发布2024-12-17 13:08:49
发布2024-12-17 13:08:49
7400
代码可运行
举报
文章被收录于专栏:云计算linux云计算linux
运行总次数:0
代码可运行

CartServlet参考代码 :

代码语言:javascript
代码运行次数:0
复制
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进行存放值,就是开篇我们的方法之一,但是这种方法有什么问题呢?大家好好思考下!!!

下面是购物车代码参考:

代码语言:javascript
代码运行次数:0
复制
<%@ 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代码参考如下:

代码语言:javascript
代码运行次数:0
复制
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");
  }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-03-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档