Java-springboot生鲜电商项目(五)购物车模块

2024-02-25 12:40

本文主要是介绍Java-springboot生鲜电商项目(五)购物车模块,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Java-springboot生鲜电商项目(五)购物车模块

  • 购物车功能
    • 涉及到的接口,购物车模块(都是前台的)
    • 业务流程
    • 总结
    • 常见错误
      • (一)购物车列表
      • dao
      • mapper
      • service
      • (二)添加商品到购物车
      • 对用户的过滤器开发:因为购物车的功能是用户的行为操作,所以在添加商品到购物车的时候,先判断是否是用户,可以借鉴管理员过滤器的开发
      • filter包中创建UserFilter
      • 对过滤器进行config配置
      • coding到这里,我发现有个小小的笔误,我在controller中@PostMapping("")注解中,映射的地址开头有些有“/”有些没有,然后我进行统一处理,全加上了,重新测试接口,到没有发现出bug。
      • 在MallExceptionEnum中加入异常处理
      • 在common常量类中设置商品上下架以及购物车选中状态
      • cartDAO
      • cart mapper
      • service
      • controller
      • 使用postman添加商品到购物车在查询商品列表
    • (三)更新购物车接口
      • service
    • (四)删除购物车接口
      • service
      • controller
      • postman测试
    • (五)单选和反选购物车商品
      • dao
      • mapper
      • service
      • controller
    • (六)全选和全不选购物车商品
      • service:不用谢productId,这样就能将所有的购物车商品选中,将全部查询出来
      • controller
      • postman

购物车功能

  1. 添加商品到购物车
  2. 全选和全不选
  3. 增加数量

涉及到的接口,购物车模块(都是前台的)

  1. 购物车列表
  2. 添加商品到购物车
  3. 更新购物车某个商品的数量
  4. 删除购物车的某个商品
  5. 选中/不选中购物车的某个商品
  6. 全选/全不选购物车的某个商品

业务流程

  1. 判断商品是否存在,提示用户
  2. 商品是否在购物车,添加商品和追加商品

总结

  1. mybatis返回非标准对象,后期计算单样商品的总价
  2. 添加商品到购物车时,根据是否已经存在该商品,有不同逻辑

常见错误

  1. 不做越权判断

(一)购物车列表

dao

List<CartVO> selectList(@Param("userId") Integer userId);

mapper

  <select id="selectList" resultType="com.hyb.mall.model.vo.CartVO" parameterType="java.lang.Integer">selectc.id as id,p.id as productId,c.user_id as userId,c.quantity as quantity,c.selected as selected,p.price as price,p.name as productName,p.image as productImagefrom imooc_mall_cart cleft join imooc_mall_product p on p.id = c.product_idwhere c.user_id =#{userId}and p.status = 1</select>

service

    @Overridepublic List<CartVO> list(Integer userId) {List<CartVO> cartVOS = cartMapper.selectList(userId);//计算总价for (int i = 0; i < cartVOS.size(); i++) {CartVO cartVO = cartVOS.get(i);cartVO.setTotalPrice(cartVO.getPrice() * cartVO.getQuantity());}return cartVOS;}

(二)添加商品到购物车

对用户的过滤器开发:因为购物车的功能是用户的行为操作,所以在添加商品到购物车的时候,先判断是否是用户,可以借鉴管理员过滤器的开发

filter包中创建UserFilter

package com.hyb.mall.filter;
import com.hyb.mall.common.Constant;
import com.hyb.mall.model.pojo.User;
import com.hyb.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;/*** 描述:用户校验过滤器* 登录后做更深层的校验,可以拿到用户信息*/
public class UserFilter implements Filter {//登录后,能将用户信息保存下来public static User currentUser;@Autowiredprivate UserService userService;@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;HttpSession session = request.getSession();//1.获取session中的用户currentUser = (User) session.getAttribute(Constant.HYB_MALL_USER);//2.判断当前用户是否为空,为空则需要登录if (currentUser == null) {PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse)servletResponse).getWriter();out.write("{\n" +"    \"status\": 10007,\n" +"    \"msg\": \"NEED_LOGIN\",\n" +"    \"data\": null\n" +"}");out.flush();out.close();return;}//3.通过用户校验filterChain.doFilter(servletRequest,servletResponse);}@Overridepublic void destroy() {}
}

对过滤器进行config配置

package com.hyb.mall.config;import com.hyb.mall.filter.AdminFilter;
import com.hyb.mall.filter.UserFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** 描述:用户过滤器的配置*/
@Configuration
public class UserFilterConfig {@Beanpublic UserFilter userFilter(){return new UserFilter();}//将整个filter放到整个链路中去@Bean(name = "userFilterConf") //设置的名字不能和类名一样不然会有冲突public FilterRegistrationBean adminFilterConfig(){FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();filterRegistrationBean.setFilter(userFilter());//设置拦截的URLfilterRegistrationBean.addUrlPatterns("/cart/*");filterRegistrationBean.addUrlPatterns("/order/*");//给过滤器配置设置名字,以便于区分不同的名字filterRegistrationBean.setName("UserFilterConfig");return filterRegistrationBean;}
}

coding到这里,我发现有个小小的笔误,我在controller中@PostMapping("")注解中,映射的地址开头有些有“/”有些没有,然后我进行统一处理,全加上了,重新测试接口,到没有发现出bug。

在MallExceptionEnum中加入异常处理

NOT_SALE(10016,"商品状态不可售"),
NOT_ENOUGH(10016,"商品库存不足"),

在common常量类中设置商品上下架以及购物车选中状态

    /*** 增加商品的上下架状态*/public interface SaleStatus{int NOT_SALE = 0;//商品的下架状态int SALE = 1;//商品的上架状态}/*** 购物车是否选中状态*/public interface Cart{int UN_CHCKED = 0;//购物车未选中int CHCKED = 1;//购物车选中}

cartDAO

 Cart selectCartByUserIdAndProduct(@Param("userId") Integer userId,@Param("productId") Integer productId);

cart mapper

  <select id="selectCartByUserIdAndProduct" resultMap="BaseResultMap" parameterType="map">select<include refid="Base_Column_List"/>from imooc_mall_cartwhere user_id = #{userId}and product_id = #{productId}</select>

service

package com.hyb.mall.service.impl;import com.hyb.mall.common.Constant;
import com.hyb.mall.exception.MallException;
import com.hyb.mall.exception.MallExceptionEnum;
import com.hyb.mall.model.dao.CartMapper;
import com.hyb.mall.model.dao.ProductMapper;
import com.hyb.mall.model.pojo.Cart;
import com.hyb.mall.model.pojo.Product;
import com.hyb.mall.model.vo.CartVO;
import com.hyb.mall.service.CartSrvice;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** 描述:购物车service实现类*/
@Service
public class CartSrviceImpl implements CartSrvice {@AutowiredProductMapper productMapper;@AutowiredCartMapper cartMapper;@Overridepublic List<CartVO> add(Integer userId, Integer productId, Integer count){validProduct(productId,count);Cart cart = cartMapper.selectCartByUserIdAndProduct(userId, productId);//判断查出来的cart是不是为空if (cart == null) {//这个商品之前不再购物车,需要新增一个记录cart = new Cart();cart.setProductId(productId);cart.setUserId(userId);cart.setQuantity(count);cart.setSelected(Constant.Cart.CHCKED);cartMapper.insertSelective(cart);}else {//这个商品已经在购物车里了,则数量相加count = cart.getQuantity() +count;Cart cartNew = new Cart();cartNew.setQuantity(count);cartNew.setId(cart.getId());cartNew.setProductId(cart.getProductId());cartNew.setUserId(cart.getUserId());cartNew.setSelected(Constant.Cart.CHCKED);cartMapper.updateByPrimaryKeySelective(cartNew);}return this.list(userId);}//验证添加是不是合法的private void validProduct(Integer productId, Integer count) {Product product = productMapper.selectByPrimaryKey(productId);//判断商品是否存在,商品是否上架if (product == null  || product.getStatus().equals(Constant.SaleStatus.NOT_SALE)) {throw new MallException(MallExceptionEnum.NOT_SALE);}//判断商品库存if (count > product.getStock()){throw new MallException(MallExceptionEnum.NOT_ENOUGH);}}}

controller

package com.hyb.mall.controller;import com.hyb.mall.common.ApiRestResponse;
import com.hyb.mall.filter.UserFilter;
import com.hyb.mall.service.CartSrvice;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;/*** 描述:购物车controller*/
@RestController
@RequestMapping("/cart")
public class CartController {@AutowiredCartSrvice cartSrvice;@ApiOperation("添加商品到购物车")@PostMapping("/add")public ApiRestResponse add(@RequestParam Integer productId,@RequestParam Integer count){List<CartVO> cartVOList = cartSrvice.add(UserFilter.currentUser.getId(), productId, count);return ApiRestResponse.success(cartVOList);}
}

使用postman添加商品到购物车在查询商品列表

在这里插入图片描述
在这里插入图片描述

(三)更新购物车接口

service

    //更新购物车@Overridepublic List<CartVO> update(Integer userId, Integer productId, Integer count) {validProduct(productId, count);Cart cart = cartMapper.selectCartByUserIdAndProduct(userId, productId);//判断查出来的cart是不是为空if (cart == null) {//这个商品之前不再购物车,无法更新throw new MallException(MallExceptionEnum.UPDATE_FAILED);} else {//这个商品已经在购物车里了,则更新数量Cart cartNew = new Cart();cartNew.setQuantity(count);cartNew.setId(cart.getId());cartNew.setProductId(cart.getProductId());cartNew.setUserId(cart.getUserId());cartNew.setSelected(Constant.Cart.CHCKED);cartMapper.updateByPrimaryKeySelective(cartNew);}return this.list(userId);}
    @ApiOperation("更新购物车")@PostMapping("/update")public ApiRestResponse update(@RequestParam Integer productId,@RequestParam Integer count) {List<CartVO> cartVOList = cartSrvice.update(UserFilter.currentUser.getId(), productId, count);return ApiRestResponse.success(cartVOList);}

(四)删除购物车接口

service

    //删除购物车商品@Overridepublic List<CartVO> delete(Integer userId, Integer productId) {Cart cart = cartMapper.selectCartByUserIdAndProduct(userId, productId);//判断查出来的cart是不是为空if (cart == null) {//这个商品之前不再购物车,无法删除throw new MallException(MallExceptionEnum.DELETE_FAILE);} else {//这个商品已经在购物车里了,则可以删除cartMapper.deleteByPrimaryKey(cart.getId());}return this.list(userId);}

controller

    @ApiOperation("删除购物车")@PostMapping("/delete")public ApiRestResponse delete(@RequestParam Integer productId) {//不能传入userID和cartID,防止黑客攻击List<CartVO> cartVOList = cartSrvice.delete(UserFilter.currentUser.getId(), productId);return ApiRestResponse.success(cartVOList);}

postman测试

在这里插入图片描述
在这里插入图片描述

(五)单选和反选购物车商品

dao

    Integer selectOrNot(@Param("userId") Integer userId,@Param("productId") Integer productId,@Param("selected") Integer selected);

mapper

  <update id="selectOrNot" parameterType="map">update imooc_mall_cartset selected = #{selected}where user_id = #{userId}<if test="productId !=null">and product_id = #{productId}</if></update>

service

    //单选和反选购物车的商品@Overridepublic List<CartVO> selectOrNot(Integer userId, Integer productId, Integer selected){//将购物车查询出来Cart cart = cartMapper.selectCartByUserIdAndProduct(userId, productId);//判断查出来的cart是不是为空if (cart == null) {//这个商品之前不再购物车,无法更新throw new MallException(MallExceptionEnum.UPDATE_FAILED);} else {//这个商品已经在购物车里了,则可以删除cartMapper.selectOrNot(userId,productId,selected);}return this.list(userId);}

controller

    @ApiOperation("单选和反选购物车的某商品")@PostMapping("/select")public ApiRestResponse select(@RequestParam Integer productId,@RequestParam Integer selected) {//不能传入userID和cartID,防止黑客攻击List<CartVO> cartVOList = cartSrvice.selectOrNot(UserFilter.currentUser.getId(), productId,selected);return ApiRestResponse.success(cartVOList);}

(六)全选和全不选购物车商品

service:不用谢productId,这样就能将所有的购物车商品选中,将全部查询出来

    //全选和全不选购物车商品@Overridepublic List<CartVO> selectAllOrNot(Integer userId, Integer selected) {//改变选中状态cartMapper.selectOrNot(userId, null, selected);return this.list(userId);}

controller

    @ApiOperation("全选和全不选购物车商品")@PostMapping("/selectAll")public ApiRestResponse selectAll(@RequestParam Integer productId,@RequestParam Integer selected) {//不能传入userID和cartID,防止黑客攻击List<CartVO> cartVOList = cartSrvice.selectAllOrNot(UserFilter.currentUser.getId(),selected);return ApiRestResponse.success(cartVOList);}

postman

在这里插入图片描述

这篇关于Java-springboot生鲜电商项目(五)购物车模块的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/745514

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

部署Vue项目到服务器后404错误的原因及解决方案

《部署Vue项目到服务器后404错误的原因及解决方案》文章介绍了Vue项目部署步骤以及404错误的解决方案,部署步骤包括构建项目、上传文件、配置Web服务器、重启Nginx和访问域名,404错误通常是... 目录一、vue项目部署步骤二、404错误原因及解决方案错误场景原因分析解决方案一、Vue项目部署步骤

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.