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
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...