1.創(chuàng)建數(shù)據(jù)表
1.使用use命令先選中store數(shù)據(jù)庫
USE store;
2.在store數(shù)據(jù)庫中創(chuàng)建t_cart用戶數(shù)據(jù)表
CREATE TABLE t_cart (
cid INT AUTO_INCREMENT COMMENT '購物車數(shù)據(jù)id',
uid INT NOT NULL COMMENT '用戶id',
pid INT NOT NULL COMMENT '商品id',
price BIGINT COMMENT '加入時(shí)商品單價(jià)',
num INT COMMENT '商品數(shù)量',
created_user VARCHAR(20) COMMENT '創(chuàng)建人',
created_time DATETIME COMMENT '創(chuàng)建時(shí)間',
modified_user VARCHAR(20) COMMENT '修改人',
modified_time DATETIME COMMENT '修改時(shí)間',
PRIMARY KEY (cid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.創(chuàng)建購物車的實(shí)體類
在entity包下創(chuàng)建購物車的Cart實(shí)體類并使其繼承BaseEntity
/**購物車數(shù)據(jù)的實(shí)體類*/
public class Cart extends BaseEntity {
private Integer cid;
private Integer uid;
private Integer pid;
private Long price;
private Integer num;
/**
* get,set
* equals和hashCode
* toString
*/
}
3.持久層[Mapper]
規(guī)劃需要執(zhí)行的SQL語句
1.向購物車表中插入商品數(shù)據(jù)的SQL語句
insert into t_cart (除了cid以外的所有字段) values (匹配的值列表);
2.如果當(dāng)前商品已經(jīng)在購物車存在,則直接更新商品即可
update t_cart set num=? where cid=?
3.在插入或者更新具體執(zhí)行哪個(gè)語句,取決于數(shù)據(jù)庫中是否有當(dāng)前的這個(gè)購物車商品的數(shù)據(jù),需要查詢語句才能確定
select * from t_cart where uid=? and pid=?
2設(shè)計(jì)接口和抽象方法
在mapper包下創(chuàng)建CartMapper接口,并添加抽象方法
public interface CartMapper {
/**
* 插入購物車數(shù)據(jù)
* @param cart 購物車數(shù)據(jù)
* @return 受影響的行數(shù)
*/
Integer insert(Cart cart);
/**
* 修改購物車數(shù)據(jù)中商品的數(shù)量
* @param cid 購物車數(shù)據(jù)的id
* @param num 新的數(shù)量
* @param modifiedUser 修改執(zhí)行人
* @param modifiedTime 修改時(shí)間
* @return 受影響的行數(shù)
*/
Integer updateNumByCid(
@Param("cid") Integer cid,
@Param("num") Integer num,
@Param("modifiedUser") String modifiedUser,
@Param("modifiedTime") Date modifiedTime);
/**
* 根據(jù)用戶id和商品id查詢購物車中的數(shù)據(jù)
* @param uid 用戶id
* @param pid 商品id
* @return 匹配的購物車數(shù)據(jù),如果該用戶的購物車中并沒有該商品,則返回null
*/
Cart findByUidAndPid(
@Param("uid") Integer uid,
@Param("pid") Integer pid);
}
3編寫映射
在resources.mapper文件夾下創(chuàng)建CartMapper.xml文件,并在文件中配置以上三個(gè)方法的映射
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//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>
<!-- 插入購物車數(shù)據(jù)-->
<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>
<!-- 修改購物車數(shù)據(jù)中商品的數(shù)量-->
<update id="updateNumByCid">
update t_cart set
num=#{num},
modified_user=#{modifiedUser},
modified_time=#{modifiedTime}
where cid=#{cid}
</update>
<!-- 根據(jù)用戶id和商品id查詢購物車中的數(shù)據(jù)-->
<select id="findByUidAndPid" resultMap="CartEntityMap">
select * from t_cart where uid=#{uid} AND pid=#{pid}
</select>
</mapper>
4單元測試
創(chuàng)建CartMapperTests測試類進(jìn)行測試
@RunWith(SpringRunner.class)
@SpringBootTest
public class CartMapperTests {
@Autowired
private CartMapper cartMapper;
@Test
public void insert() {
Cart cart = new Cart();
cart.setUid(11);
cart.setPid(10000001);
cart.setNum(3);
cart.setPrice(4L);//長整型
cartMapper.insert(cart);
}
@Test
public void updateNumByCid() {
cartMapper.updateNumByCid(1, 4, "張三", new Date());
}
@Test
public void findByUidAndPid() {
Cart cart = cartMapper.findByUidAndPid(11, 10000001);
System.out.println(cart);
}
}
4.業(yè)務(wù)層[Service]
1規(guī)劃異常
在插入數(shù)據(jù)時(shí),可能拋出InsertException異常;在修改數(shù)據(jù)時(shí),可能拋出UpdateException異常.這兩個(gè)異常已開發(fā)
2設(shè)計(jì)接口和抽象方法及實(shí)現(xiàn)
1.在com.cy.store.service包下創(chuàng)建ICartService接口,并添加抽象方法
該抽象方法都需要哪些參數(shù)呢,還是依據(jù)持久層,看持久層三條sql語句的實(shí)現(xiàn)需要什么參數(shù):
findByUidAndPid:查詢購物車數(shù)據(jù),參數(shù)是uid,pid
insert:插入購物車數(shù)據(jù),參數(shù)是cart對象(屬性有cid,uid,pid,price,num)
updateNumByCid:修改購物車中商品數(shù)量,參數(shù)是cid,num,modifiedUser,modifiedTime
price可以通過業(yè)務(wù)層中調(diào)用ProductMapper接口的findById獲取,modifiedTime在業(yè)務(wù)層實(shí)現(xiàn)類的內(nèi)部創(chuàng)建,所以需要的參數(shù)是uid,pid,num,username
經(jīng)過這次分析結(jié)合以前給業(yè)務(wù)層方法聲明參數(shù),可以發(fā)現(xiàn)即使持久層的方法參數(shù)是實(shí)體類對象,業(yè)務(wù)層的方法參數(shù)也大多不是實(shí)體類對象,因?yàn)閷?shí)體類的部分屬性是可以在業(yè)務(wù)層進(jìn)行拼接然后封裝到實(shí)體類對象中,再傳給持久層(比如這里的price),這樣的話就降低了前端傳遞數(shù)據(jù)的壓力,如果該對象的所有方法都必須由前端傳遞過來,那么業(yè)務(wù)層方法參數(shù)可以是實(shí)體類對象(如注冊用戶時(shí)業(yè)務(wù)層的方法參數(shù)就是User對象)
public interface ICartService {
/**
* 將商品添加到購物車
* @param uid 當(dāng)前登錄用戶的id
* @param pid 商品的id
* @param amount 增加的數(shù)量
* @param username 當(dāng)前登錄的用戶名
*/
void addToCart(Integer uid, Integer pid, Integer amount, String username);
}
2.創(chuàng)建CartServiceImpl類,并實(shí)現(xiàn)ICartService接口.在類中聲明CartMapper持久層對象和IProductService處理商品數(shù)據(jù)的業(yè)務(wù)對象,并實(shí)現(xiàn)業(yè)務(wù)層的抽象方法
@Service
public class ICartServiceImpl implements ICartService {
/*
由于購物車的業(yè)務(wù)依賴于購物車和商品的持久層,若通過session獲取數(shù)據(jù)
*/
@Autowired
private CartMapper cartMapper;
@Autowired
private ProductMapper productMapper;
@Override
public void addToCart(Integer uid, Integer pid, Integer amount, String username) {
//查詢購物車是否已經(jīng)存在【查看用戶之前是否將該商品加入過購物車】
Cart result = cartMapper.findByUidAndPid(uid, pid);
Date date = new Date();
if(result == null) {//新增商品
Cart cart = new Cart();
//封裝數(shù)據(jù):uid,pid,amount
cart.setUid(uid);
cart.setPid(pid);
cart.setNum(amount);
//查詢商品數(shù)據(jù),得到商品價(jià)格進(jìn)行封裝
Product product = productMapper.findById(pid);
cart.setPrice(product.getPrice());
//封裝數(shù)據(jù):4個(gè)日志
cart.setCreatedUser(username);
cart.setCreatedTime(date);
cart.setModifiedUser(username);
cart.setModifiedTime(date);
Integer rows = cartMapper.insert(cart);
if(rows != 1) {
throw new InsertException("未知異常 在 插入數(shù)據(jù)");
}
} else {//更新num值
//從查詢結(jié)果中取出原數(shù)量,與參數(shù)amount相加,得到新的數(shù)量
Integer num = result.getNum() + amount;//加入購物車時(shí)只會有+不可能有-
Integer rows = cartMapper.updateNumByCid(result.getCid(), num, username, date);
if(rows != 1) {
throw new UpdateException("未知異常 在 更新數(shù)據(jù)");
}
}
}
}
3單元測試
創(chuàng)建測試類CartServiceTests并編寫測試方法。
@RunWith(SpringRunner.class)
@SpringBootTest
public class CartServiceTests {
@Autowired
private ICartService cartService;
@Test
public void addToCart() {
cartService.addToCart(11, 10000002, 5, "Tom");
}
}
5.控制層[Contrroller]
1處理異常
InsertException異常和UpdateException異常都已經(jīng)設(shè)置到BaseController類中了,這里無需重復(fù)開發(fā)
2設(shè)計(jì)請求
- /carts/add_to_cart
- post
- Integer pid, Integer amount, HttpSession session
- JsonResult<Void>
3處理請求
在controller包下創(chuàng)建CartController類并繼承BaseController類,在類中添加處理請求的addToCart()方法
@RestController
@RequestMapping("carts")
public class CartController extends BaseController {
@Autowired
private ICartService cartService;
@RequestMapping("add_to_cart")
public JsonResult<Void> addToCart(Integer pid, Integer amount, HttpSession session) {
cartService.addToCart(
getUidFromSession(session),
pid,
amount,
getUsernameFromSession(session));
return new JsonResult<Void>(OK);
}
}
6.前端頁面
在product.html頁面中的body標(biāo)簽內(nèi)的script標(biāo)簽里為“加入購物車”按鈕添加點(diǎn)擊事件
回顧一下在ajax函數(shù)中data參數(shù)的數(shù)據(jù)設(shè)置的方式
- data:$(“選擇的form表單”).serialize()。當(dāng)需要提交的參數(shù)過多并且在同一個(gè)表單中時(shí)使用
- data:new FormData($(“選擇的form表單”)[0])。只適用提交文件
- data:“username=TOM”。手動(dòng)拼接,適合參數(shù)值固定并且參數(shù)值列表有限.等同于
var user = "控件某屬性值或控件文本內(nèi)容或自己聲明的值"
data: "username="+user
- 使用JSON格式提交數(shù)據(jù)
data: {
"username": "Tom",
"age": 18
}
-
使用RestFul風(fēng)格不屬于前端給后端傳參數(shù)
這里表單里面有很多無用參數(shù),所以不使用表單提交文章來源:http://www.zghlxwxcb.cn/news/detail-707758.html
$("#btn-add-to-cart").click(function() {
$.ajax({
url: "/carts/add_to_cart",
type: "POST",
data: {
"pid": id,
"amount": $("#num").val()
},
dataType: "JSON",
success: function(json) {
if (json.state == 200) {
alert("增加成功!");
} else {
alert("增加失??!" + json.message);
}
},
error: function(xhr) {
alert("您的登錄信息已經(jīng)過期,請重新登錄!HTTP響應(yīng)碼:" + xhr.status);
location.href = "login.html";
}
});
});
點(diǎn)擊"加入購物車"按鈕后頁面跳轉(zhuǎn)的實(shí)現(xiàn):product.html導(dǎo)入的product.js文件里面實(shí)現(xiàn)了點(diǎn)擊后跳轉(zhuǎn)文章來源地址http://www.zghlxwxcb.cn/news/detail-707758.html
到了這里,關(guān)于SpringBoot項(xiàng)目--電腦商城【加入購物車】的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!