day09-功能實現08

来源:https://www.cnblogs.com/liyuelian/archive/2022/12/26/17007004.html
-Advertisement-
Play Games

家居網購項目實現08 以下皆為部分代碼,詳見 https://github.com/liyuelian/furniture_mall.git 19.功能18-添加家居到購物車 19.1需求分析/圖解 會員登錄後,可以添加家居到購物車 完成購物車的設計和實現 每添加一個家居,購物車的數量+1並顯示 1 ...


家居網購項目實現08

以下皆為部分代碼,詳見 https://github.com/liyuelian/furniture_mall.git

19.功能18-添加家居到購物車

19.1需求分析/圖解

image-20221224193256396
  1. 會員登錄後,可以添加家居到購物車
  2. 完成購物車的設計和實現
  3. 每添加一個家居,購物車的數量+1並顯示

19.2思路分析

說明:這裡實現的購物車是session版的,不是資料庫版的。也就是說,用戶購物車的數據在退出登錄或者退出瀏覽器後將會清空。

如果希望將購物車放到mysql中,將Cart數據模型改成一張表即可,即Entity和表的一種映射概念,你可以使用Entity-DAO-Service。大概做法就是購物車表和CartItem實體映射,表的一行記錄就是一個cartItem類。通過記錄用戶id和用戶聯繫起來。

JavaEE+mvc模式:

image-20221224200840580

19.3代碼實現

19.3.1entity層

CartItem.java

package com.li.furns.entity;

import java.math.BigDecimal;

/**
 * CartItem 表示購物車的一項,就是某個家居數據
 *
 * @author 李
 * @version 1.0
 */
public class CartItem {
    //定義屬性->根據需求
    private Integer id; //家居id
    private String name; //家居名
    private BigDecimal price; //家居單價
    private Integer count; //家居數量
    private BigDecimal totalPrice; //總價格

    public CartItem() {
    }

    public CartItem(Integer id, String name, BigDecimal price, Integer count, BigDecimal totalPrice) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.count = count;
        this.totalPrice = totalPrice;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public BigDecimal getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(BigDecimal totalPrice) {
        this.totalPrice = totalPrice;
    }

    @Override
    public String toString() {
        return "CartItem{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", count=" + count +
                ", totalPrice=" + totalPrice +
                '}';
    }
}

Cart.java

image-20221224215000376
package com.li.furns.entity;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Set;

/**
 * Cart就是一個購物車,包含很多CartItem對象
 *
 * @author 李
 * @version 1.0
 */
public class Cart {
    //定義屬性
    //包含多個CartItem對象,使用HashMap來保存
    private HashMap<Integer, CartItem> items = new HashMap<>();

    //添加家居CartItem到Cart
    public void addItem(CartItem cartItem) {
        //添加cartItem到Cart前要先判斷-該item是第一次添加還是二次以後添加
        //使用家居id在items中找有沒有對應家居
        CartItem item = items.get(cartItem.getId());
        if (null == item) {//說明當前購物車還沒有這個cartItem
            //添加該cartItem到購物車Cart中去
            items.put(cartItem.getId(), cartItem);
        } else {//當前購物車已經有這個cartItem
            //數量增加1
            item.setCount(item.getCount() + 1);
            //修改總價
            //item.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getCount())));
            item.setTotalPrice(item.getTotalPrice().add(item.getPrice()));
        }
    }

    @Override
    public String toString() {
        return "Cart{" +
                "items=" + items +
                '}';
    }
}

19.3.2test

CartTest.java

package com.li.furns.test;

import com.li.furns.entity.Cart;
import com.li.furns.entity.CartItem;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;

/**
 * @author 李
 * @version 1.0
 */
public class CartTest {
    private Cart cart = new Cart();

    @Test
    public void addItem() {
        cart.addItem(new CartItem(1, "沙發", new BigDecimal(10), 2, new BigDecimal(20)));
        cart.addItem(new CartItem(2, "小椅子", new BigDecimal(20), 2, new BigDecimal(40)));
        System.out.println("cart=>" + cart);
    }
}

19.3.3web層

配置CartServlet

<servlet>
    <servlet-name>CartServlet</servlet-name>
    <servlet-class>com.li.furns.web.CartServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>CartServlet</servlet-name>
    <url-pattern>/cartServlet</url-pattern>
</servlet-mapping>

CartServlet.java

package com.li.furns.web;

import com.li.furns.entity.Cart;
import com.li.furns.entity.CartItem;
import com.li.furns.entity.Furn;
import com.li.furns.service.FurnService;
import com.li.furns.service.impl.FurnServiceImpl;
import com.li.furns.utils.DataUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 李
 * @version 1.0
 */

public class CartServlet extends BasicServlet {
    //增加一個屬性
    private FurnService furnService = new FurnServiceImpl();

    /**
     * 添加家居數據到購物車
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //得到添加的家居ID
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        //獲取到id對應的Furn對象
        Furn furn = furnService.queryFurnById(id);
        if (furn == null) {//說明沒有查到對應的家居信息
            return;
            //todo
        }
        //根據furn構建CartItem
        CartItem item =
                new CartItem(furn.getId(), furn.getName(), furn.getPrice(), 1, furn.getPrice());
        //從session獲取cart對象
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (null == cart) {//說明當前的session沒有cart對象
            //創建一個cart對象
            cart = new Cart();
            //將其放入到session中
            req.getSession().setAttribute("cart", cart);
        }
        //將cartItem加入到cart對象
        cart.addItem(item);

        //添加完畢後需要返回到添加家居的頁面
        String referer = req.getHeader("Referer");
        resp.sendRedirect(referer);
    }
}

19.3.4修改前端介面

views/cutomer/index.jsp

點擊add to cart按鈕,添加家居信息到購物車中

<script type="text/javascript">
    $(function () {
        //給add to cart綁定事件
        $("button.add-to-cart").click(function () {
            //獲取到點擊的furn-id
            var furnId = $(this).attr("furnId");
            //發出一個請求-添加家居=>後面改成ajax
            location.href = "cartServlet?action=addItem&id=" + furnId;
        })
    })
</script>

顯示購物車信息

image-20221226194414905

19.4完成測試

未添加家居前購物車顯示

image-20221226194649712

點擊add to cart,添加家居到購物車

image-20221226194726996 image-20221226194741603

添加多個家居信息

image-20221226194812983

20.功能19-顯示購物車

20.1需求分析/圖解

image-20221226195433397
  1. 查看購物車,可以顯示如上信息
  2. 選中了哪些家居,名稱,數量,金額
  3. 統計購物車共多少商品,總價多少

20.2思路分析

image-20221226200708298

20.3代碼實現

Cart.java

為了配合前端介面,增加一些方法

public HashMap<Integer, CartItem> getItems() {
    return items;
}

public BigDecimal getCartTotalPrice() {
    BigDecimal cartTotalPrice = new BigDecimal(0);
    //遍歷購物車,返回整個購物車的商品總價格
    Set<Integer> keys = items.keySet();
    for (Integer id : keys) {
        CartItem item = items.get(id);
        //一定要把add後的值重新賦給cartTotalPrice
        cartTotalPrice = cartTotalPrice.add(item.getTotalPrice());
    }
    return cartTotalPrice;
}

public int getTotalCount() {
    //因為前端每點擊一次添加商品,購物車顯示就會調用getTotalCount方法,
    //如果不置0,數量相當是重覆添加
    int totalCount = 0;
    //遍歷購物車,返回商品總數量
    Set<Integer> keys = items.keySet();
    for (Integer id : keys) {
        totalCount += ((CartItem) items.get(id)).getCount();
    }
    return totalCount;
}

用foreach在cart.jsp迴圈顯示購物車信息

<!-- Cart Area Start -->
<div class="cart-main-area pt-100px pb-100px">
<div class="container">
<h3 class="cart-page-title">Your cart items</h3>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-12">
<form action="#">
<div class="table-content table-responsive cart-table-content">
<table>
<thead>
<tr>
<th>圖片</th>
<th>家居名</th>
<th>單價</th>
<th>數量</th>
<th>金額</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<%--找到顯示的購物車項,進行迴圈顯示--%>
<c:if test="${not empty sessionScope.cart.items}">
<%--
1.items實際上是HashMap<Integer, CartItem>
2.所以通過foreach標簽取出的每一個對象entry 是 HashMap<Integer, CartItem> 的k-v
3.因此var其實就是entry
4.所以要取出cartItem是通過entry.value
--%>
<c:forEach items="${sessionScope.cart.items}" var="entry">
    <tr>
        <td class="product-thumbnail">
            <a href="#"><img class="img-responsive ml-3"
                             src="assets/images/product-image/1.jpg"
                             alt=""/></a>
        </td>
        <td class="product-name"><a href="#">${entry.value.name}</a></td>
        <td class="product-price-cart"><span class="amount">${entry.value.price}</span></td>
        <td class="product-quantity">
            <div class="cart-plus-minus">
                <input class="cart-plus-minus-box" type="text" name="qtybutton"
                       value="${entry.value.count}"/>
            </div>
        </td>
        <td class="product-subtotal">${entry.value.totalPrice}</td>
        <td class="product-remove">
            <a href="#"><i class="icon-close"></i></a>
        </td>
    </tr>
</c:forEach>
</c:if>
</tbody>
</table>
</div>
<div class="row">
<div class="col-lg-12">
<div class="cart-shiping-update-wrapper">
<h4>共${sessionScope.cart.totalCount}件商品 總價 ${sessionScope.cart.cartTotalPrice}元</h4>
<div class="cart-shiping-update">
    <a href="#">購 物 車 結 賬</a>
</div>
<div class="cart-clear">
    <button>繼 續 購 物</button>
    <a href="#">清 空 購 物 車</a>
</div>
</div>
</div>
</div>
</form>

</div>
</div>
</div>
</div>
<!-- Cart Area End -->

20.4完成測試

image-20221226210923105

21.功能20-修改購物車

21.1需求分析/圖解

image-20221226211829037
  1. 進入購物車頁面,可以修改購買數量
  2. 更新該商品的金額
  3. 更新購物車商品數量和總金額

21.2思路分析


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 移動設備硬體的高速發展,讓游戲行業發生翻天覆地的變化,許多酷炫的游戲效果不再局限於電腦端,玩家在移動端就能享受到場景更逼真、畫質更清晰、體驗更流暢的游戲服務。但由於移動設備算力不足,為了實現真實感的水體效果,很多游戲廠商採用預計算的方法減少實時模擬的計算開銷,但水體場景在移動端的流體效果仍然不佳。 ...
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 前段時間,對部門的個別項目進行Vue3.0+ts框架的遷移,剛開始研究的時候也是踩坑特別多,尤其我們的項目還有些特殊的webpack配置,所以,研究vue.config.js的配置的時候也是查閱了各種資料文檔,最終,完成了項目webpac ...
  • 在 JavaScript 中,有時候你可能會發現 0.1+0.2 不等於 0.3。這是因為 JavaScript 使用的是浮點數來表示小數,而浮點數在電腦內部是用二進位表示的,這導致了一些精度問題。 ...
  • 在 JavaScript 中,巨集任務和微任務是指在執行代碼的過程中的兩種不同的任務類型。 巨集任務(macro task)指的是瀏覽器在執行代碼的過程中會調度的任務,比如事件迴圈中的每一次迭代、setTimeout 和 setInterval 等。巨集任務會在瀏覽器完成當前同步任務之後執行。 微任務(m... ...
  • 今天,收到一個很有意思的提問,如何實現類似如下的背景效果圖: 嗯?核心主體是由多個六邊形網格疊加形成。 那麼我們該如何實現它呢?使用純 CSS 能夠實現嗎? 當然可以,下麵我們就將嘗試如何使用 CSS 去實現這樣一個背景效果。 如何繪製六邊形? 首先,看到這樣一個圖形,如果想要使用一個標簽完成整個背 ...
  • 序 2020 年 10 月 17 日,我正式發佈了 Fantastic-admin 這款基於 Vue 的中後臺管理系統框架。在這兩年多的時間里,我陸續寫了幾篇我在開發這套框架中的一些心得和技術總結: 2020 年《我是如何設計後臺框架里那些錦上添花的動畫效果》 2020 年《一勞永逸,解決基於 ke ...
  • 1 String不可變性 String類被聲明為 final,因此它不可被繼承。 內部使用char數組存儲數據,該數組被聲明為final,這意味著value數組初始化之後就不能再指向其它數組。 String內部沒有改變value數組的方法 String類中所有修改String值的方法,如果內容沒有改 ...
  • ​ 一、前言 本篇文章內容為個人學習分享,讀代碼須知以下 樂理的基本知識,以及十二平均律(波的頻率與音高的標準),個人推薦在維基百科中搜索十二平均律表。 二、整體思想 在主函數中,將一些簡單的樂譜按照節拍,按鍵,基調,半音改變經行拆解。 然後我個人學習時,以440hz為標準的do依次類推,得到的基礎 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...