• 购物车模块开发


    注意:new BigDecimal()的参数必须是String类型,否则还是会存在精度问题。

    CartController:
    package com.mmall.controller.portal;
    
    import com.mmall.common.Const;
    import com.mmall.common.ResponseCode;
    import com.mmall.common.ServerResponse;
    import com.mmall.pojo.User;
    import com.mmall.service.ICartService;
    import com.mmall.vo.CartVo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.servlet.http.HttpSession;
    
    /**
     * Created by geely
     */
    @Controller
    @RequestMapping("/cart/")
    public class CartController {
    
        @Autowired
        private ICartService iCartService;
    
    
    
        @RequestMapping("list.do")
        @ResponseBody
        public ServerResponse<CartVo> list(HttpSession session){
            User user = (User)session.getAttribute(Const.CURRENT_USER);
            if(user ==null){
                return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
            }
            return iCartService.list(user.getId());
        }
    
        @RequestMapping("add.do")
        @ResponseBody
        public ServerResponse<CartVo> add(HttpSession session, Integer count, Integer productId){
            User user = (User)session.getAttribute(Const.CURRENT_USER);
            if(user ==null){
                return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
            }
            return iCartService.add(user.getId(),productId,count);
        }
    
    
    
        @RequestMapping("update.do")
        @ResponseBody
        public ServerResponse<CartVo> update(HttpSession session, Integer count, Integer productId){
            User user = (User)session.getAttribute(Const.CURRENT_USER);
            if(user ==null){
                return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
            }
            return iCartService.update(user.getId(),productId,count);
        }
    
        @RequestMapping("delete_product.do")
        @ResponseBody
        public ServerResponse<CartVo> deleteProduct(HttpSession session,String productIds){
            User user = (User)session.getAttribute(Const.CURRENT_USER);
            if(user ==null){
                return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
            }
            return iCartService.deleteProduct(user.getId(),productIds);
        }
    
    
        @RequestMapping("select_all.do")
        @ResponseBody
        public ServerResponse<CartVo> selectAll(HttpSession session){
            User user = (User)session.getAttribute(Const.CURRENT_USER);
            if(user ==null){
                return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
            }
            return iCartService.selectOrUnSelect(user.getId(),null,Const.Cart.CHECKED);
        }
    
        @RequestMapping("un_select_all.do")
        @ResponseBody
        public ServerResponse<CartVo> unSelectAll(HttpSession session){
            User user = (User)session.getAttribute(Const.CURRENT_USER);
            if(user ==null){
                return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
            }
            return iCartService.selectOrUnSelect(user.getId(),null,Const.Cart.UN_CHECKED);
        }
    
    
    
        @RequestMapping("select.do")
        @ResponseBody
        public ServerResponse<CartVo> select(HttpSession session,Integer productId){
            User user = (User)session.getAttribute(Const.CURRENT_USER);
            if(user ==null){
                return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
            }
            return iCartService.selectOrUnSelect(user.getId(),productId,Const.Cart.CHECKED);
        }
    
        @RequestMapping("un_select.do")
        @ResponseBody
        public ServerResponse<CartVo> unSelect(HttpSession session,Integer productId){
            User user = (User)session.getAttribute(Const.CURRENT_USER);
            if(user ==null){
                return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
            }
            return iCartService.selectOrUnSelect(user.getId(),productId,Const.Cart.UN_CHECKED);
        }
    
    
    
        @RequestMapping("get_cart_product_count.do")
        @ResponseBody
        public ServerResponse<Integer> getCartProductCount(HttpSession session){
            User user = (User)session.getAttribute(Const.CURRENT_USER);
            if(user ==null){
                return ServerResponse.createBySuccess(0);
            }
            return iCartService.getCartProductCount(user.getId());
        }
    
    
    
    
        //全选
        //全反选
    
        //单独选
        //单独反选
    
        //查询当前用户的购物车里面的产品数量,如果一个产品有10个,那么数量就是10.
    
    
    
    
    }
    CartMapper:
    package com.mmall.dao;
    
    import com.mmall.pojo.Cart;
    import org.apache.ibatis.annotations.Param;
    
    import java.util.List;
    
    public interface CartMapper {
        int deleteByPrimaryKey(Integer id);
    
        int insert(Cart record);
    
        int insertSelective(Cart record);
    
        Cart selectByPrimaryKey(Integer id);
    
        int updateByPrimaryKeySelective(Cart record);
    
        int updateByPrimaryKey(Cart record);
    
        Cart selectCartByUserIdProductId(@Param("userId") Integer userId, @Param("productId") Integer productId);
    
        List<Cart> selectCartByUserId(Integer userId);
    
        int selectCartProductCheckedStatusByUserId(Integer userId);
    
        int deleteByUserIdProductIds(@Param("userId") Integer userId, @Param("productIdList") List<String> productIdList);
    
    
        int checkedOrUncheckedProduct(@Param("userId") Integer userId, @Param("productId") Integer productId, @Param("checked") Integer checked);
    
        int selectCartProductCount(@Param("userId") Integer userId);
    
    
        List<Cart> selectCheckedCartByUserId(Integer userId);
    
    
    }
    CartServiceImpl:
    package com.mmall.service.impl;
    
    import com.google.common.base.Splitter;
    import com.google.common.collect.Lists;
    import com.mmall.common.Const;
    import com.mmall.common.ResponseCode;
    import com.mmall.common.ServerResponse;
    import com.mmall.dao.CartMapper;
    import com.mmall.dao.ProductMapper;
    import com.mmall.pojo.Cart;
    import com.mmall.pojo.Product;
    import com.mmall.service.ICartService;
    import com.mmall.util.BigDecimalUtil;
    import com.mmall.util.PropertiesUtil;
    import com.mmall.vo.CartProductVo;
    import com.mmall.vo.CartVo;
    import org.apache.commons.collections.CollectionUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.math.BigDecimal;
    import java.util.List;
    
    /**
     * Created by geely
     */
    @Service("iCartService")
    public class CartServiceImpl implements ICartService {
    
        @Autowired
        private CartMapper cartMapper;
        @Autowired
        private ProductMapper productMapper;
    
        public ServerResponse<CartVo> add(Integer userId, Integer productId, Integer count) {
            if (productId == null || count == null) {
                return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
            }
    
    
            Cart cart = cartMapper.selectCartByUserIdProductId(userId, productId);
            if (cart == null) {
                //这个产品不在这个购物车里,需要新增一个这个产品的记录
                Cart cartItem = new Cart();
                cartItem.setQuantity(count);
                cartItem.setChecked(Const.Cart.CHECKED);
                cartItem.setProductId(productId);
                cartItem.setUserId(userId);
                cartMapper.insert(cartItem);
            } else {
                //这个产品已经在购物车里了.
                //如果产品已存在,数量相加
                count = cart.getQuantity() + count;
                cart.setQuantity(count);
                cartMapper.updateByPrimaryKeySelective(cart);
            }
            return this.list(userId);
        }
    
        public ServerResponse<CartVo> update(Integer userId, Integer productId, Integer count) {
            if (productId == null || count == null) {
                return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
            }
            Cart cart = cartMapper.selectCartByUserIdProductId(userId, productId);
            if (cart != null) {
                cart.setQuantity(count);
            }
            cartMapper.updateByPrimaryKey(cart);
            return this.list(userId);
        }
    
        public ServerResponse<CartVo> deleteProduct(Integer userId, String productIds) {
            List<String> productList = Splitter.on(",").splitToList(productIds);
            if (CollectionUtils.isEmpty(productList)) {
                return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
            }
            cartMapper.deleteByUserIdProductIds(userId, productList);
            return this.list(userId);
        }
    
    
        public ServerResponse<CartVo> list(Integer userId) {
            CartVo cartVo = this.getCartVoLimit(userId);
            return ServerResponse.createBySuccess(cartVo);
        }
    
    
        public ServerResponse<CartVo> selectOrUnSelect(Integer userId, Integer productId, Integer checked) {
            cartMapper.checkedOrUncheckedProduct(userId, productId, checked);
            return this.list(userId);
        }
    
        public ServerResponse<Integer> getCartProductCount(Integer userId) {
            if (userId == null) {
                return ServerResponse.createBySuccess(0);
            }
            return ServerResponse.createBySuccess(cartMapper.selectCartProductCount(userId));
        }
    
    
        private CartVo getCartVoLimit(Integer userId) {
            CartVo cartVo = new CartVo();
            List<Cart> cartList = cartMapper.selectCartByUserId(userId);
            List<CartProductVo> cartProductVoList = Lists.newArrayList();
    
            BigDecimal cartTotalPrice = new BigDecimal("0");
    
            if (CollectionUtils.isNotEmpty(cartList)) {
                for (Cart cartItem : cartList) {
                    CartProductVo cartProductVo = new CartProductVo();
                    cartProductVo.setId(cartItem.getId());
                    cartProductVo.setUserId(userId);
                    cartProductVo.setProductId(cartItem.getProductId());
    
                    Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
                    if (product != null) {
                        cartProductVo.setProductMainImage(product.getMainImage());
                        cartProductVo.setProductName(product.getName());
                        cartProductVo.setProductSubtitle(product.getSubtitle());
                        cartProductVo.setProductStatus(product.getStatus());
                        cartProductVo.setProductPrice(product.getPrice());
                        cartProductVo.setProductStock(product.getStock());
                        //判断库存
                        int buyLimitCount = 0;
                        if (product.getStock() >= cartItem.getQuantity()) {
                            //库存充足的时候
                            buyLimitCount = cartItem.getQuantity();
                            cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                        } else {
                            buyLimitCount = product.getStock();
                            cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
                            //购物车中更新有效库存
                            Cart cartForQuantity = new Cart();
                            cartForQuantity.setId(cartItem.getId());
                            cartForQuantity.setQuantity(buyLimitCount);
                            cartMapper.updateByPrimaryKeySelective(cartForQuantity);
                        }
                        cartProductVo.setQuantity(buyLimitCount);
                        //计算总价
                        cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartProductVo.getQuantity()));
                        cartProductVo.setProductChecked(cartItem.getChecked());
                    }
    
                    if (cartItem.getChecked() == Const.Cart.CHECKED) {
                        //如果已经勾选,增加到整个的购物车总价中
                        cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVo.getProductTotalPrice().doubleValue());
                    }
                    cartProductVoList.add(cartProductVo);
                }
            }
            cartVo.setCartTotalPrice(cartTotalPrice);
            cartVo.setCartProductVoList(cartProductVoList);
            cartVo.setAllChecked(this.getAllCheckedStatus(userId));
            cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
    
            return cartVo;
        }
    
        private boolean getAllCheckedStatus(Integer userId) {
            if (userId == null) {
                return false;
            }
            return cartMapper.selectCartProductCheckedStatusByUserId(userId) == 0;
    
        }
    
    
    }
    ICartService:
    package com.mmall.service;
    
    import com.mmall.common.ServerResponse;
    import com.mmall.vo.CartVo;
    
    /**
     * Created by geely
     */
    public interface ICartService {
        ServerResponse<CartVo> add(Integer userId, Integer productId, Integer count);
        ServerResponse<CartVo> update(Integer userId, Integer productId, Integer count);
        ServerResponse<CartVo> deleteProduct(Integer userId, String productIds);
    
        ServerResponse<CartVo> list(Integer userId);
        ServerResponse<CartVo> selectOrUnSelect(Integer userId, Integer productId, Integer checked);
        ServerResponse<Integer> getCartProductCount(Integer userId);
    }
    CartProductVo:
    package com.mmall.vo;
    
    import java.math.BigDecimal;
    
    /**
     * Created by geely
     */
    public class CartProductVo {
    
    //结合了产品和购物车的一个抽象对象
    
        private Integer id;
        private Integer userId;
        private Integer productId;
        private Integer quantity;//购物车中此商品的数量
        private String productName;
        private String productSubtitle;
        private String productMainImage;
        private BigDecimal productPrice;
        private Integer productStatus;
        private BigDecimal productTotalPrice;
        private Integer productStock;
        private Integer productChecked;//此商品是否勾选
    
        private String limitQuantity;//限制数量的一个返回结果
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public Integer getUserId() {
            return userId;
        }
    
        public void setUserId(Integer userId) {
            this.userId = userId;
        }
    
        public Integer getProductId() {
            return productId;
        }
    
        public void setProductId(Integer productId) {
            this.productId = productId;
        }
    
        public Integer getQuantity() {
            return quantity;
        }
    
        public void setQuantity(Integer quantity) {
            this.quantity = quantity;
        }
    
        public String getProductName() {
            return productName;
        }
    
        public void setProductName(String productName) {
            this.productName = productName;
        }
    
        public String getProductSubtitle() {
            return productSubtitle;
        }
    
        public void setProductSubtitle(String productSubtitle) {
            this.productSubtitle = productSubtitle;
        }
    
        public String getProductMainImage() {
            return productMainImage;
        }
    
        public void setProductMainImage(String productMainImage) {
            this.productMainImage = productMainImage;
        }
    
        public BigDecimal getProductPrice() {
            return productPrice;
        }
    
        public void setProductPrice(BigDecimal productPrice) {
            this.productPrice = productPrice;
        }
    
        public Integer getProductStatus() {
            return productStatus;
        }
    
        public void setProductStatus(Integer productStatus) {
            this.productStatus = productStatus;
        }
    
        public BigDecimal getProductTotalPrice() {
            return productTotalPrice;
        }
    
        public void setProductTotalPrice(BigDecimal productTotalPrice) {
            this.productTotalPrice = productTotalPrice;
        }
    
        public Integer getProductStock() {
            return productStock;
        }
    
        public void setProductStock(Integer productStock) {
            this.productStock = productStock;
        }
    
        public Integer getProductChecked() {
            return productChecked;
        }
    
        public void setProductChecked(Integer productChecked) {
            this.productChecked = productChecked;
        }
    
        public String getLimitQuantity() {
            return limitQuantity;
        }
    
        public void setLimitQuantity(String limitQuantity) {
            this.limitQuantity = limitQuantity;
        }
    }
    CartVo:
    package com.mmall.vo;
    
    import java.math.BigDecimal;
    import java.util.List;
    
    /**
     * Created by geely
     */
    public class CartVo {
    
        private List<CartProductVo> cartProductVoList;
        private BigDecimal cartTotalPrice;
        private Boolean allChecked;//是否已经都勾选
        private String imageHost;
    
        public List<CartProductVo> getCartProductVoList() {
            return cartProductVoList;
        }
    
        public void setCartProductVoList(List<CartProductVo> cartProductVoList) {
            this.cartProductVoList = cartProductVoList;
        }
    
        public BigDecimal getCartTotalPrice() {
            return cartTotalPrice;
        }
    
        public void setCartTotalPrice(BigDecimal cartTotalPrice) {
            this.cartTotalPrice = cartTotalPrice;
        }
    
        public Boolean getAllChecked() {
            return allChecked;
        }
    
        public void setAllChecked(Boolean allChecked) {
            this.allChecked = allChecked;
        }
    
        public String getImageHost() {
            return imageHost;
        }
    
        public void setImageHost(String imageHost) {
            this.imageHost = imageHost;
        }
    }

    CartMapper:

    <?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.mmall.dao.CartMapper" >
      <resultMap id="BaseResultMap" type="com.mmall.pojo.Cart" >
        <constructor >
          <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
          <arg column="user_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
          <arg column="product_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
          <arg column="quantity" jdbcType="INTEGER" javaType="java.lang.Integer" />
          <arg column="checked" jdbcType="INTEGER" javaType="java.lang.Integer" />
          <arg column="create_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
          <arg column="update_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
        </constructor>
      </resultMap>
      <sql id="Base_Column_List" >
        id, user_id, product_id, quantity, checked, create_time, update_time
      </sql>
      <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select 
        <include refid="Base_Column_List" />
        from mmall_cart
        where id = #{id,jdbcType=INTEGER}
      </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from mmall_cart
        where id = #{id,jdbcType=INTEGER}
      </delete>
      <insert id="insert" parameterType="com.mmall.pojo.Cart" >
        insert into mmall_cart (id, user_id, product_id, 
          quantity, checked, create_time, 
          update_time)
        values (#{id,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER}, #{productId,jdbcType=INTEGER}, 
          #{quantity,jdbcType=INTEGER}, #{checked,jdbcType=INTEGER}, now(),
          now())
      </insert>
      <insert id="insertSelective" parameterType="com.mmall.pojo.Cart" >
        insert into mmall_cart
        <trim prefix="(" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            id,
          </if>
          <if test="userId != null" >
            user_id,
          </if>
          <if test="productId != null" >
            product_id,
          </if>
          <if test="quantity != null" >
            quantity,
          </if>
          <if test="checked != null" >
            checked,
          </if>
          <if test="createTime != null" >
            create_time,
          </if>
          <if test="updateTime != null" >
            update_time,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            #{id,jdbcType=INTEGER},
          </if>
          <if test="userId != null" >
            #{userId,jdbcType=INTEGER},
          </if>
          <if test="productId != null" >
            #{productId,jdbcType=INTEGER},
          </if>
          <if test="quantity != null" >
            #{quantity,jdbcType=INTEGER},
          </if>
          <if test="checked != null" >
            #{checked,jdbcType=INTEGER},
          </if>
          <if test="createTime != null" >
            now(),
          </if>
          <if test="updateTime != null" >
            now(),
          </if>
        </trim>
      </insert>
      <update id="updateByPrimaryKeySelective" parameterType="com.mmall.pojo.Cart" >
        update mmall_cart
        <set >
          <if test="userId != null" >
            user_id = #{userId,jdbcType=INTEGER},
          </if>
          <if test="productId != null" >
            product_id = #{productId,jdbcType=INTEGER},
          </if>
          <if test="quantity != null" >
            quantity = #{quantity,jdbcType=INTEGER},
          </if>
          <if test="checked != null" >
            checked = #{checked,jdbcType=INTEGER},
          </if>
          <if test="createTime != null" >
            create_time = #{createTime,jdbcType=TIMESTAMP},
          </if>
          <if test="updateTime != null" >
            update_time = now(),
          </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
      </update>
      <update id="updateByPrimaryKey" parameterType="com.mmall.pojo.Cart" >
        update mmall_cart
        set user_id = #{userId,jdbcType=INTEGER},
          product_id = #{productId,jdbcType=INTEGER},
          quantity = #{quantity,jdbcType=INTEGER},
          checked = #{checked,jdbcType=INTEGER},
          create_time = #{createTime,jdbcType=TIMESTAMP},
          update_time = now()
        where id = #{id,jdbcType=INTEGER}
      </update>
    
    
      <select id="selectCartByUserIdProductId" resultMap="BaseResultMap" parameterType="map">
        SELECT
        <include refid="Base_Column_List"/>
        from mmall_cart
        where user_id = #{userId}
        and product_id = #{productId}
      </select>
    
    
    
      <select id="selectCartByUserId" resultMap="BaseResultMap" parameterType="int">
        SELECT
        <include refid="Base_Column_List"/>
        from mmall_cart
        where user_id = #{userId}
      </select>
    
      <select id="selectCartProductCheckedStatusByUserId" resultType="int" parameterType="int">
        SELECT  count(1) from mmall_cart where checked = 0 and user_id = #{userId}
      </select>
      
      
      <delete id="deleteByUserIdProductIds" parameterType="map">
        delete from mmall_cart
        where user_id = #{userId}
        <if test="productIdList != null">
          and product_id in
          <foreach collection="productIdList" item="item" index="index" open="(" separator="," close=")">
            #{item}
          </foreach>
        </if>
      </delete>
    
    
    
      <update id="checkedOrUncheckedProduct" parameterType="map">
        UPDATE  mmall_cart
        set checked = #{checked},
        update_time = now()
        where user_id = #{userId}
        <if test="productId != null">
          and product_id = #{productId}
        </if>
      </update>
    
    
      <select id="selectCartProductCount" parameterType="int" resultType="int">
        select IFNULL(sum(quantity),0) as count from mmall_cart where user_id = #{userId}
      </select>
    
    
    
      <select id="selectCheckedCartByUserId" parameterType="int" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        from mmall_cart
        where user_id = #{userId}
        and checked = 1
      </select>
    
    </mapper>
  • 相关阅读:
    leetcode 189. Rotate Array 数组旋转 ---------- java
    Google test Problem A. Country Leader
    leetcode 187. Repeated DNA Sequences 求重复的DNA串 ---------- java
    mysql忘记密码(未初始化)
    leetcode 186. Reverse Words in a String II 旋转字符数组 ---------- java
    CSS3属性transform详解之(旋转:rotate,缩放:scale,倾斜:skew,移动:translate)(转载)
    bootstrap
    bootstrap使用中遇到的问题(二)
    兼容ie8 rgba()用法
    浏览器前缀
  • 原文地址:https://www.cnblogs.com/XJJD/p/8528211.html
Copyright © 2020-2023  润新知