• SpringBoot项目--电脑商城【增加/减少购物车商品数量】


    1.持久层[Mapper]

    1.1规划需要执行的SQL语句

    1.更新该商品的数量.此SQL语句无需重复开发

    update t_cart set num=?,modified_user=?,modified_time=? where cid=?

    2.首先进行查询需要操作的购物车数据信息【查看该条数据是否存在】

    SELECT * FROM t_cart WHERE cid=?
    

    2.接口和抽象方法

    在CartMapper接口中添加抽象方法

    Cart findByCid(Integer cid);
    

    3 编写映射

    在CartMapper文件中添加findByCid(Integer cid)方法的映射

    1. <select id="findByCid" resultMap="CartEntityMap">
    2. select *
    3. from t_cart
    4. where cid=#{cid};
    5. select>

    4 单元测试

    在CartMapperTests测试类中添加findByCid()测试方法

    1. @Test
    2. public void findByCid() {
    3. System.out.println(cartMapper.findByCid(1));
    4. }

    2.业务层[service]

    1规划异常

    • 在更新时产生UpdateException未知异常,此异常类无需再次创建
    • 可能该购物车列表数据归属不是登录的用户,抛AccessDeniedException异常,此异常类无需再次创建
    • 要查询的数据不存在.抛出CartNotFoundException异常,创建该异常类并使其继承ServiceException
    1. /** 购物车数据不存在的异常 */
    2. public class CartNotFoundException extends ServiceException {
    3. /**重写ServiceException的所有构造方法*/
    4. }

    2设计接口和抽象方法及实现

    在业务层ICartService接口中添加addNum()抽象方法

    1.先判断需要哪些参数,该抽象方法的实现依赖于CartMapper接口的两个方法:

    updateNumByCid方法.参数是cid,num,String modifiedUser,Date modifiedTime

    findByCid方法.参数是cid

    在业务层中从购物车表查询到该商品的数量,然后再和前端传过来的增加的数量进行求和得到num

    所以该方法的参数是cid,uid,username

    2.判断一下该方法的返回值:

    • 该方法返回值void.这样的话就需要在前端页面加location.href使该页面自己跳转到自己,实现刷新页面(不建议,每次都加载整个页面,数据量太大了)
    • 返回值是Integer类型.这样的话就把数据库中更新后的数量层层传给前端,前端接收后填充到控件中就可以了
    1. /**
    2. * 增加用户的购物车中某商品的数量
    3. * @param cid
    4. * @param uid
    5. * @param username
    6. * @return 增加成功后新的数量
    7. */
    8. Integer addNum(Integer cid,Integer uid, String username);

    3.在CartServiceImpl类中实现接口中的抽象方法

    1. /**
    2. * 更新用户的购物车数量的数据
    3. *
    4. * 调用了updateNumByCid(cid,num,modifiedUser,modifiedTime)
    5. * 和findByCid(cid)
    6. * Integer:返回的是最新的购物车数量
    7. */
    8. @Override
    9. public Integer addNum(Integer cid, Integer uid, String username) {
    10. Cart result = cartMapper.findByCid(cid);
    11. if(result == null) {
    12. throw new CartNotFoundException("购物车数据不存在");
    13. } else if(! result.getUid().equals(uid)) {
    14. throw new AccessDeniedException("数据非法访问");
    15. }
    16. Integer num = result.getNum() + 1;
    17. Integer rows = cartMapper.updateNumByCid(cid, num, username, new Date());
    18. if(rows != 1) {
    19. throw new UpdateException("更新数据失败");
    20. }
    21. return num;
    22. }

    3单元测试

    就接收个参数,然后业务层将其加一后返回,不需要再测了

    3.控制层[Controller]

    1处理异常

    在BaseController类中添加CartNotFoundException异常类的统一管理

    1. else if (e instanceof CartNotFoundException) {
    2. result.setState(4007);
    3. result.setMessage("购物车表不存在该商品的异常");
    4. }

    2设计请求

    • /carts/{cid}/num/add
    • post
    • @PathVariable(“cid”) Integer cid, HttpSession session
    • JsonResult

    3处理请求

    在CartController类中添加处理请求的addNum()方法

    1. @PostMapping("/{cid}/add_num")
    2. public JsonResult addNum(@PathVariable("cid") Integer cid,
    3. HttpSession session){
    4. Integer data = cartService.addNum(cid,
    5. getuidFromSession(session),
    6. getUsernameFromSession(session));
    7. return new JsonResult<>(OK,data);
    8. }

    4.前端页面

    1.首先确定在showCartList()函数中动态拼接的增加购物车按钮是绑定了addNum()事件,如果已经添加无需重复添加

    "num-btn" type="button" value="+" onclick="addNum(#{cid})" />
    

    2.在script标签中定义addNum()函数并编写增加购物车数量的逻辑代码

    1. //添加商品按钮
    2. function addNum(cid){
    3. $.ajax({
    4. url:"/cart/"+cid+"/add_num",
    5. type: "POST",
    6. dataType:"JSON",
    7. success(e){
    8. console.log(e.state)
    9. if (e.state==200){
    10. //
    11. //修改商品数量,
    12. // val(): 因为这里使用val,是为了修改value的值
    13. $("#goodsCount" + cid).val(e.data);
    14. //¥#{singlePrice}
    15. //商品单价
    16. //html():选中所选元素的html,可能有html元素
    17. let singlePrice=$("#goodsPrice"+cid).html();
    18. let totalPrice=singlePrice*e.data;
    19. //表示将总数加入页面中
    20. //#{totalPrice}
    21. $("#goodsCast"+cid).html(totalPrice);
    22. }else{
    23. alert("增加购物车数据失败"+e.message)
    24. }
    25. },
    26. error(xhr){
    27. alert("增加购物车商品数据加载产生未知的异常"+xhr.status)
    28. }
    29. })
    30. }

    1.持久层[Mapper]

    1.规划需要执行的SQL语句

    1.判断当前要删除的商品是否还存在[原来的findById]

    selct * from t_cart where uid=? and cid=?

    2.如果该商品在该用户的购物车中本来就有,则对其的操作是进行数据更新[原来的updateNumByCid]

    2.接口和抽象方法

    1.在CartMapper.java

    1. /**
    2. * 修改购物车数据中商品的数量
    3. * @param cid 购物车数据的id
    4. * @param num 新的数量
    5. * @param modifiedUser 修改执行人
    6. * @param modifiedTime 修改时间
    7. * @return 受影响的行数
    8. */
    9. Integer updateNumByCid(
    10. @Param("cid") Integer cid,
    11. @Param("num") Integer num,
    12. @Param("modifiedUser") String modifiedUser,
    13. @Param("modifiedTime") Date modifiedTime);
    14. /**
    15. * 根据用户id和商品id查询购物车中的数据
    16. * @param uid 用户id
    17. * @param pid 商品id
    18. * @return 匹配的购物车数据,如果该用户的购物车中并没有该商品,则返回null
    19. */
    20. Cart findByUidAndPid(
    21. @Param("uid") Integer uid,
    22. @Param("pid") Integer pid);

    3.编写映射

    1. <update id="updateNumByCid">
    2. update t_cart set
    3. num=#{num},
    4. modified_user=#{modifiedUser},
    5. modified_time=#{modifiedTime}
    6. where cid=#{cid}
    7. update>
    8. <select id="findByUidAndPid" resultMap="CartEntityMap">
    9. select * from t_cart where uid=#{uid} AND pid=#{pid}
    10. select>

    4.测试代码

    此测试代码可以省略

    2.业务层[Service]

    1.规划异常

    • 在删除的时候,可能该数据被删除,造成删除异常
    • 在更新时产生UpdateException未知异常,此异常类无需再次创建
    • 可能该购物车列表数据归属不是登录的用户,抛AccessDeniedException异常,此异常类无需再次创建
    • 要查询的数据不存在.抛出CartNotFoundException异常,创建该异常类并使其继承ServiceException

    2.设计接口和抽象方法的实现

    1.ICartService

    1. /**
    2. * 更新用户的购物车数据--减少
    3. * @param cid
    4. * @param uid
    5. * @param username
    6. * @return
    7. */
    8. Integer subNum(Integer cid,Integer uid,String username);

    2.ICartServiceImpl

    1. /**
    2. * 更新用户的购物车数据--减少
    3. * @param cid
    4. * @param uid
    5. * @param username
    6. * @return
    7. */
    8. @Override
    9. public Integer subNum(Integer cid, Integer uid, String username) {
    10. Cart result = cartMapper.findByCid(cid);
    11. if(result==null){
    12. throw new CartNotFoundException("购物车数据不存在");
    13. }
    14. if(!result.getUid().equals(uid)){
    15. throw new AccessDeniedException("数据非法访问");
    16. }
    17. Integer num=result.getNum()-1;
    18. Integer rows = cartMapper.updateNumByCid(cid, num, username, new Date());
    19. if(rows!=1){
    20. throw new UpdateException("更新数据失败");
    21. }
    22. return num;
    23. }

    3.单元测试

    1. @Test
    2. public void subNum(){
    3. cartService.subNum(3,7,"管理员");
    4. }

    3.控制层[Controller]

    1.处理异常

    前面增加功能已经实现,不用重复执行

    2.设计请求

    • /cart/sub_num/{cid}
    • post
    • @PathVariable("cid") Integer cid,HttpSession session
    • JsonResult

    3.处理请求

    1. /**
    2. * 在购物车列表中减少商品数量
    3. * @param cid
    4. * @param session
    5. * @return
    6. */
    7. @PostMapping("/sub_num/{cid}")
    8. public JsonResult subNum(@PathVariable("cid") Integer cid,
    9. HttpSession session){
    10. Integer data = cartService.subNum(cid,
    11. getuidFromSession(session),
    12. getUsernameFromSession(session));
    13. return new JsonResult<>(OK,data);
    14. }

    4.前端页面

    1.首先确定在showCartList()函数中动态拼接的增加购物车按钮是绑定了reduceNum()事件,如果已经添加无需重复添加

    "price-#{cid}"  type="button" value="-" class="num-btn" onclick="reduceNum(#{cid})" />

    1. function reduceNum(cid) {
    2. $.ajax({
    3. url: "/cart/sub_num/"+cid,
    4. type: "POST",
    5. dataType: "JSON",
    6. success: function(json) {
    7. if (json.state == 200) {
    8. // showCartList();
    9. $("#goodsCount" + cid).val(json.data);
    10. let price = $("#goodsPrice" + cid).html();
    11. let totalPrice = price * json.data;
    12. $("#goodsCast" + cid).html(totalPrice);
    13. } else {
    14. alert("修改商品数量失败!" + json.message);
    15. }
    16. },
    17. error: function(xhr) {
    18. alert("您的登录信息已经过期,请重新登录!HTTP响应码:" + xhr.status);
    19. location.href = "login.html";
    20. }
    21. });
    22. }

  • 相关阅读:
    插件创建Maven工程
    语音人工智能的简单介绍
    层次分析法求权重和最大特征值MATLAB代码(个人记录)
    【Mqtt】学习MQTT利器 之 Mosquitto服务器的开源实现
    3-1、python内置数据类型(字符串类型)
    VM虚拟机无法拖拽、粘贴、复制
    Elasticsearch--easy-ES框架使用,轻松操作查询Elasticsearch,简化开发
    【常见算法】第三篇:回溯算法
    [python]常用配置读取方法
    【LLM】基于LLM的agent应用(上)
  • 原文地址:https://blog.csdn.net/m0_63077733/article/details/132824236