SpringBoot電腦商城項目--商品詳情+加入購物車

商品詳情

1. 持久層

1.1. 規劃sql語句

? ? ? ? 根據id查詢商品詳情

1.2 mapper層編寫抽象方法

    /*** 根據商品id查詢商品詳情* @param id 商品id* @return 匹配的id商品詳情,如果沒有匹配的數據,則返回null*/Product findById(Integer id);

1.3 xml文件中編寫sql映射

? ? ? ? 查到的數據要封裝成resultMap結果集

    <select id="findById" resultMap="ProductEntityMap">select * from t_product where id=#{id}</select>

2.?業務層

2.1 規劃異常

? ? ? ? 根據id查詢商品信息時可能會出現找不到的異常,需要定義一個ProductNotFoundException類

package com.cy.store.service.ex;/** 商品數據不存在的異常 */
public class ProductNotFoundException extends ServiceException {public ProductNotFoundException() {super();}public ProductNotFoundException(String message) {super(message);}public ProductNotFoundException(String message, Throwable cause) {super(message, cause);}public ProductNotFoundException(Throwable cause) {super(cause);}protected ProductNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}
}

2.2 在Service類編寫接口和抽象方法

    /** 根據商品id查詢商品詳情 */Product findById(Integer id);

2.3 實現類實現接口重寫抽象方法

    /*** 根據商品id查詢商品詳情* @param id 商品id* @return 匹配的id商品詳情,如果沒有匹配的數據,則返回null*/@Overridepublic Product findById(Integer id) {Product product = productMapper.findById(id);// 判斷查詢結果是否為nullif (product == null) {throw new ProductNotFoundException("嘗試訪問的商品數據不存在");}// 將查詢結果中的部分屬性設置為nullproduct.setPriority(null);product.setCreatedUser(null);product.setCreatedTime(null);product.setModifiedUser(null);product.setModifiedTime(null);return product;}

3. 控制層

3.1 捕獲異常

? ? ? ? 在BaseController中捕獲ProductNotFoundException異常

else if (e instanceof ProductNotFoundException){result.setState(4006);result.setMessage("商品數據不存在");}

3.2 controller實現請求

    /*** 獲取商品詳情* @param id 商品id* @return 商品詳情*/@RequestMapping("/details/{id}")public JsonResult<Product> getById(@PathVariable("id") Integer id){Product data = productService.findById(id);return new JsonResult<>(OK,data);}

4. 前端頁面

? ? ? ? product.html頁面

		<!-- 引入用于獲取URL參數的jQuery插件,以便后續JS代碼中獲取商品ID --><script type="text/javascript" src="../js/jquery-getUrlParam.js"></script><script type="text/javascript">// 文檔加載完成后執行以下代碼$(document).ready(function () {// 使用 jQuery 插件 getUrlParam 獲取 URL 中的 "id" 參數值,即商品IDvar id = $.getUrlParam("id");console.log("id=" + id);// 發起 AJAX 請求獲取該商品的詳細信息$.ajax({url: "/products/details/"+ id, // 請求地址type: "GET", // 請求方法為 GETsuccess: function (json) { // 請求成功時的回調函數if (json.state == 200) { // 如果返回狀態碼為 200,表示請求成功console.log("title=" + json.data.title);// 將商品標題、賣點、價格填充到頁面對應元素中$("#product-title").html(json.data.title);$("#product-sell-point").html(json.data.sellPoint);$("#product-price").html(json.data.price);// 循環更新5張商品圖片的路徑(大圖和縮略圖)for (var i = 1; i <= 5; i++) {$("#product-image-" + i + "-big").attr("src", ".." + json.data.image + i + "_big.png");$("#product-image-" + i).attr("src", ".." + json.data.image + i + ".jpg");}} else if (json.state == 4006) { // 如果商品數據不存在,則跳轉回首頁location.href = "index.html";} else { // 其他錯誤情況彈出提示信息alert("獲取商品信息失敗!" + json.message);}}});});</script>

加入購物車

1. 在數據庫中創建購物車的表(t_cart)

CREATE TABLE t_cart (cid INT AUTO_INCREMENT COMMENT '購物車數據id',uid INT NOT NULL COMMENT '用戶id',pid INT NOT NULL COMMENT '商品id',price BIGINT COMMENT '加入時商品單價',num INT COMMENT '商品數量',created_user VARCHAR(20) COMMENT '創建人',created_time DATETIME COMMENT '創建時間',modified_user VARCHAR(20) COMMENT '修改人',modified_time DATETIME COMMENT '修改時間',PRIMARY KEY (cid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. 創建Cart實體類

? ? ? ? @Data:是Lombok提供的注解,自動生成類的getter、setter、toString等方法

package com.cy.store.entity;import lombok.Data;/**購物車數據的實體類*/
@Data
public class Cart extends BaseEntity {private Integer cid;private Integer uid;private Integer pid;private Long price;private Integer num;
}

3. 持久層

3.1 規劃sql語句

  • 向購物車表中插入數據

insert into t_cart () value()

  • 如果當前商品已經存在與購物車中,則直接更新數量num就行

update t_cart set
? ? ? ? ? ? num=#{num},
? ? ? ? ? ? modified_user=#{modifiedUser},
? ? ? ? ? ? modified_time=#{modifiedTime}
? ? ? ? where cid=#{cid}

  • 在插入或者更新具體執行哪個語句,取決于數據庫中是否有當前這個購物車商品的數量,得去查詢才能確定

select * from t_cart where uid=#{uid} AND pid=#{pid}

3.2 創建CartMapper接口,編寫抽象方法

@Mapper
public interface CartMapper {/*** 插入購物車數據* @param cart 購物車數據* @return 受影響的行數*/Integer insert(Cart cart);/*** 根據用戶id和商品id修改購物車數據* @param cid 購物車id* @param num 修改之后的數量* @param modifiedUser 修改執行人* @param modifiedTime 修改時間* @return*/Integer updateNumByCid(Integer cid,Integer num,String modifiedUser,Date modifiedTime);/*** 根據用戶id和商品id查詢購物車數據* @param uid 用戶id* @param pid 商品id* @return 匹配的購物車數據,如果沒有匹配的數據則返回null*/Cart findByUidAndPid(Integer uid, Integer pid);}

3.3 在CartMapper.xml文件中進行sql映射以及sql的編寫

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.store.mapper.CartMapper"><resultMap id="CartEntityMap" type="com.cy.store.entity.Cart"><id column="cid" property="cid"/><result column="created_user" property="createdUser"/><result column="created_time" property="createdTime"/><result column="modified_user" property="modifiedUser"/><result column="modified_time" property="modifiedTime"/></resultMap><!-- 插入購物車數據--><insert id="insert" useGeneratedKeys="true" keyProperty="cid">insert into t_cart (uid, pid, price, num, created_user, created_time, modified_user, modified_time)values (#{uid}, #{pid}, #{price}, #{num}, #{createdUser}, #{createdTime}, #{modifiedUser}, #{modifiedTime})</insert><!-- 修改購物車數據中商品的數量--><update id="updateNumByCid">update t_cart setnum=#{num},modified_user=#{modifiedUser},modified_time=#{modifiedTime}where cid=#{cid}</update><!-- 根據用戶id和商品id查詢購物車中的數據--><select id="findByUidAndPid" resultMap="CartEntityMap">select * from t_cart where uid=#{uid} AND pid=#{pid}</select>
</mapper>

3.4 在CartMapperTest類中進行測試

@SpringBootTest
class CartMapperTest {@Autowiredprivate CartMapper cartMapper;@Testpublic void insert() {Cart cart = new Cart();cart.setUid(1);cart.setPid(2);cart.setNum(2);cart.setPrice(3000l);cart.setCreatedTime(new Date());cart.setModifiedTime(new Date());cart.setCreatedUser("admin1");cart.setModifiedUser("admin1");Integer rows = cartMapper.insert(cart);System.out.println(rows);}@Testpublic void updateNumByCid() {Integer rows = cartMapper.updateNumByCid(1, 2, "admin", new Date());System.out.println(rows);}@Testpublic void findByUidAndPid() {Cart cart = cartMapper.findByUidAndPid(1, 1);System.out.println(cart);}}

4.?業務層

4.1 規劃異常

  • 插入數據庫購物車數據時可能產生InsertException異常
  • 更新數據時可能出現UpdateException異常

4.2 創建CartService接口類,編寫業務層的抽象方法

? ? ? ? 更新時間這些字段可以通過new Date()獲取,所以CartService接口層只需要用戶id,商品id以及數量,更新人這些字段

package com.cy.store.service;public interface CartService {/*** 添加商品到購物車* @param uid 用戶id* @param pid 商品id* @param amount 商品數量* @param username 用戶名*/void addToCart(Integer uid, Integer pid, Integer amount, String username);}

4.3 實現類實現接口,重寫抽象方法

? ? ? ? 其中的商品價格可以通過商品表獲取,這里需要注入ProductMapper,調用根據pid獲取商品價格

@Service
public class CartServiceImpl implements CartService {@Autowiredprivate CartMapper cartMapper;@Autowiredprivate ProductMapper productMapper;/*** 添加購物車* @param uid 用戶id* @param pid 商品id* @param amount 商品數量* @param username 用戶名*/@Overridepublic void addToCart(Integer uid, Integer pid, Integer amount, String username) {
//        查詢當前用戶購物車中是否存在此商品Cart res = cartMapper.findByUidAndPid(uid, pid);Date date = new Date();//        不存在的話就添加if (res == null) {
//            補全價格Cart cart = new Cart();cart.setUid(uid);cart.setPid(pid);cart.setNum(amount);
//            獲取商品表中商品的價格,封裝到cart中Product product = productMapper.findById(pid);cart.setPrice(product.getPrice());cart.setCreatedTime(date);cart.setModifiedTime(date);cart.setCreatedUser( username);cart.setModifiedUser(username);cartMapper.insert(cart);}else {//存在的話就修改購物車中商品的數量
//            商品數量=購物車中的數量+用戶傳遞的數量amount = res.getNum()+amount;Integer integer = cartMapper.updateNumByCid(res.getCid(), amount, username, date);if (integer!=1){throw new UpdateException("更新數據時產生未知的異常");}}}
}

4.4 測試

package com.cy.store.service;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class CartServiceTest {@Autowiredprivate CartService cartService;@Testvoid addToCart() {cartService.addToCart(3, 10000001, 10, "admin");}
}

5. 控制層

5.1 設計請求

請求路徑:/carts/addToCart

請求方式:GET

請求參數:pid,amount ,session

響應數據:JsonResult<Void>

5.2 實現請求

package com.cy.store.controller;import com.cy.store.service.CartService;
import com.cy.store.util.JsonResult;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/carts")
public class CartController extends BaseController{@Autowiredprivate CartService cartService;@RequestMapping("addToCart")public JsonResult addToCart(Integer pid, Integer amount, HttpSession session) {Integer uid = getUidFromSession(session);String username = getUsernameFromSession(session);cartService.addToCart( uid,pid, amount, username);return new JsonResult<>(OK);}
}

5.3 啟動項目,測試

6. 前端頁面

? ? ? ? 在product.html頁面給【加入購物車】按鈕添加點擊事件。發送ajax請求

? ? ? ? 在ajax函數中data參數的數據設置的方式:

  • data:$("form表單名稱").seriallize():當參數過多并且在同一個表單中,字符串的提交時
  • data:new FormData($("form表單名稱")[0]):只適用于文件
  • data:"username=Tom":適合于參數值固定并且參數值列表有限,可以進行手動拼接

let user = "admin"

data:"username="+user

  • 使用JSON格式提交數據
data: {"pid": id, // 商品id"amount": $("#num").val() // 監聽數量輸入框中的值
}

代碼如下:

// 點擊“加入購物車”按鈕時觸發 AJAX 請求,將商品加入購物車(當前被注釋)$("#btn-add-to-cart").click(function() {$.ajax({url: "/carts/addToCart",type: "POST",// 通過json格式傳參data: {"pid": id, // 商品id"amount": $("#num").val() // 監聽數量輸入框中的值},dataType: "JSON",success: function(json) {if (json.state == 200) {alert("增加成功!");} else {alert("增加失敗!" + json.message);}},error: function(xhr) {alert("您的登錄信息已經過期,請重新登錄!HTTP響應碼:" + xhr.status);location.href = "login.html";}});});

? ? ? ? 重啟項目進行測試,查看數據庫是否新增成功

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/86064.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/86064.shtml
英文地址,請注明出處:http://en.pswp.cn/web/86064.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

上交卡爾動力聯合提出FastDrive!結構化標簽實現自動駕駛端到端大模型更快更強

最近將類人的推理能力融入到端到端自動駕駛系統中已經成為了一個前沿的研究領域。其中&#xff0c;基于視覺語言模型的方法已經吸引了來自工業界和學術界的廣泛關注。 現有的VLM訓練范式嚴重依賴帶有自由格式的文本標注數據集&#xff0c;如圖1(a)所示。雖然這些描述能夠捕捉豐…

C# 委托(什么是委托)

什么是委托 可以認為委托是持有一個或多個方法的對象。當然&#xff0c;一般情況下你不會想要“執行”一個對 象&#xff0c;但委托與典型的對象不同。可以執行委托&#xff0c;這時委托會執行它所“持有"的方法。 本章將揭示創建和使用委托的語法和語義。在本章后面&am…

iTwin briefcase, checkpoint ,standalone

在 iTwin.js 中&#xff0c;briefcase 和 checkpoint 都是 IModel 的不同連接類型&#xff0c;但它們的用途和特性不同&#xff1a; Briefcase 用途&#xff1a;用于本地編輯和同步。通常是用戶從 iModelHub 檢出&#xff08;Check-out&#xff09;后在本地生成的可寫副本。特…

媒體AI關鍵技術研究

一、引言 隨著人工智能技術的迅猛發展&#xff0c;媒體行業正經歷前所未有的變革。AI技術不僅重塑了內容生產和傳播模式&#xff0c;更為媒體創意發展提供了全新可能。在數字化、移動化和信息爆炸的大背景下&#xff0c;傳統媒體面臨巨大挑戰&#xff0c;而AI技術為行業帶來了…

Cargo 與 Rust 項目

一、Rust 項目&#xff1a;現代化的系統編程單元 Rust 項目 是用 Rust 語言編寫的軟件工程單元&#xff0c;具有以下核心特征&#xff1a; 核心組件&#xff1a; src/ 目錄&#xff1a;存放 Rust 源代碼&#xff08;.rs 文件&#xff09; Cargo.toml&#xff1a;項目清單文件…

uni-app總結6-配合iOS App項目開發apple watch app

假設你已經用uni-app開發好了一個iOS端的app,現在想要開發一個配套的apple watch app。改怎么去開發呢?是不是一頭霧水,這篇文章就會介紹一些apple watch app開發的知識以及如何在uni-app開發的iOS app基礎上去開發配套的watch app。 一、apple watch 開發知識 apple watc…

神經網絡的本質 邏輯回歸 python的動態展示

神經網絡的本質 邏輯回歸 python的動態展示 邏輯回歸運行圖相關代碼什么是邏輯回歸和ai的關系邏輯回歸公式流程與實際案例解析**一、邏輯回歸的數學公式流程**1. **線性組合階段**2. **激活函數&#xff08;Sigmoid&#xff09;**3. **概率預測與決策**4. **交叉熵損失函數**5.…

sql server中的with 鎖各種區別

&#x1f4d8; SQL Server 常用 WITH (Hint) 用法與組合場景對照表 Hint 組合作用說明常見用途是否阻塞他人是否讀臟數據備注WITH (NOLOCK)不加共享鎖&#xff0c;允許讀取未提交數據報表導出、大數據分頁??等價于 READ UNCOMMITTED&#xff0c;臟讀風險高WITH (HOLDLOCK)保持…

KES數據庫部署工具使用

一、啟動部署工具 Windows系統 #命令行 ${安裝目錄}/ClientTools/guitools/DeployTools/deploy.exeLinux系統 #命令行 [rootnode ~]# ${安裝目錄}/ClientTools/guitools/DeployTools/deploy二、環境配置 1.硬件要求 #都是最小配置 CPU&#xff1a;主流32或64位 內存&#…

TB62211FNG是一款采用時鐘輸入控制的PWM斬波器的兩相雙極步進電機驅動器

TB62211FNG是一款采用時鐘輸入控制的PWM斬波器的兩相雙極步進電機驅動器。該器件采用BiCD工藝制造&#xff0c;額定電壓為40伏/1.0安培。片上電壓調節器允許使用單一VM電源控制步進電機。 特點&#xff1a; ? 雙極性步進電機驅動器 ? 脈沖寬度調制&#xff08;PWM&#xf…

uni-app項目實戰筆記24--uniapp實現圖片保存到手機相冊

前提條件&#xff1a;微信小程序要想實現保存圖片到本地相冊需要到微信公眾平臺--小程序--開發管理中配置服務器域名中的downloadFile合法域名&#xff1a; \uniapp提供了saveImageToPhotosAlbum API實現保存的圖片到本地相冊。下面是它的配置參數&#xff1a; 參數名類型必填…

面試題-定義一個函數入參數是any類型,返回值是string類型,如何寫出這個函數,代碼示例

在 TypeScript 里&#xff0c;要定義一個入參為any類型、返回值為string類型的函數&#xff0c;可參考下面幾種實現方式&#xff1a; 1. 基礎實現 直接把入參轉換為字符串返回。 function anyToString(input: any): string {return String(input); // 使用String()進行類型轉…

TensorFlow深度學習實戰——Transformer模型評價指標

TensorFlow深度學習實戰——Transformer模型評價指標 0. 前言1. 質量1.1 GLUE1.2 SuperGLUE1.3 SQuAD1.4 RACE1.5 NLP-progress2. 參數規模3. 服務成本相關鏈接0. 前言 可以使用多種類型的指標評估 Transformer 模型。在本節中,我們將學習一些用于評估 Transformer 的關鍵因素…

linux內核學習(一)---內核社區介紹及補丁提交

目錄 一、引言 二、內核源碼 三、內核社區 ------>3.1、社區的組織架構 ------>3.2、內核社區的工作方式 ------>3.3、內核社區核心網站 ------------>3.3.1、Linux Kernel 官網 ------------>3.3.2、Linux Kernel 郵件列表(LKML) ------------>3.3…

輕量級web開發框架之Flask web開發框架學習:get請求數據的發送

Flask是一個使用 Python 編寫的輕量級 Web 應用框架&#xff0c;簡介靈活&#xff0c;可快速構建開發框架。 協作流程示例 客戶端請求 → Web服務器&#xff08;Nginx&#xff09; → WSGI服務器&#xff08;Gunicorn/uWSGI&#xff09;↓WSGI協議傳遞請求數據&#xff08;env…

Vue 3 異步三劍客:Suspense、async setup() 和 await 的戲劇性關系,白屏的解決

文章目錄 &#x1f3ad; Vue 3 異步三劍客&#xff1a;Suspense、async setup() 和 await 的戲劇性關系&#xff0c;白屏的解決&#x1f3ac; 角色介紹&#x1f3ad; 正常演出流程&#xff08;有 Suspense 時&#xff09;&#x1f4a5; 災難場景&#xff08;缺少 Suspense 時&a…

【JavaScript-Day 48】告別 Ajax,擁抱現代網絡請求:Fetch API 完全指南

Langchain系列文章目錄 01-玩轉LangChain&#xff1a;從模型調用到Prompt模板與輸出解析的完整指南 02-玩轉 LangChain Memory 模塊&#xff1a;四種記憶類型詳解及應用場景全覆蓋 03-全面掌握 LangChain&#xff1a;從核心鏈條構建到動態任務分配的實戰指南 04-玩轉 LangChai…

BUUCTF在線評測-練習場-WebCTF習題[極客大挑戰 2019]Knife1-flag獲取、解析

解題思路 這題沒有什么解題思路&#xff0c;打開靶場&#xff0c;標題是白給的shell 頁面顯示了 eval($_POST["Syc"]); 這是php webshell命令&#xff0c;密碼為Syc&#xff0c;可直接通過該命令連接&#xff0c;根據標題提示&#xff0c;直接嘗試用蟻劍連接 連接成…

Qt—(Qt線程,Qt進程,,QT與sqlite數據庫)

一 Qt線程與進程概述 線程與進程對比 特性線程 (QThread)進程 (QProcess)內存空間共享父進程內存獨立內存空間創建開銷小 (幾MB)大 (幾十MB)通信方式共享內存/信號槽管道/套接字/文件崩潰影響導致整個進程終止僅自身終止適用場景高并發任務、計算密集型隔離第三方應用、安全需求…

計算機視覺階段一:CV入門基礎

目錄 學習目標&#xff1a; 一、核心知識點 二、實用工具推薦 三、學習內容與步驟 1.環境搭建 2.圖像獲取與顯示 3 圖像基礎處理 4 圖像幾何變換 5 圖像像素操作 四、實戰任務建議 實戰 1&#xff1a;圖像加載 顯示 保存 實戰 2&#xff1a;灰度圖 邊緣檢測 圖…