0
点赞
收藏
分享

微信扫一扫

redis(2)

徐一村 2023-05-23 阅读 77

显示商品详情功能及加入购物车功能的实现

显示商品详情

(一)显示商品详情(持久层)

1.规划sql

select * from t_product where id=?

2.设计接口和抽象方法

    //根据id查询
    Product getById(Integer id);
    <select id="getById" resultMap="ProductEntityMap">
        select *
        from t_product where id=#{id};
    </select>


(二)显示商品详情(业务层)

2.规划异常

/** 商品数据不存在的异常 */
public class ProductNotFoundException extends ServiceException {
    /**重写ServiceException的所有构造方法*/
}

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

Product getById(Integer id);
  @Override
    public Product getById(Integer id) {

        Product product = productMapper.getById(id);
        if (product==null){
            throw new ProductNotFoundException("商品不存在");
        }
        product.setPriority(null);
        product.setCreatedUser(null);
        product.setCreatedTime(null);
        product.setModifiedUser(null);
        product.setModifiedTime(null);
        return product;
    }

(三)显示商品详情(控制层)

1.处理异常

else if (e instanceof ProductNotFoundException) {
	result.setState(4006);
    result.setMessage("访问的商品数据不存在的异常");
}

2.设计请求

3.处理请求

@GetMapping("{id}/details")
    public JsonResult<Product> getById(@PathVariable("id") Integer id){
    Product product = productService.getById(id);
   return new JsonResult<>(ok,product);
}

(四)显示商品详情(前端页面)

<script type="text/javascript" src="../js/jquery-getUrlParam.js"></script>
<script type="text/javascript">
            //调用jquery-getUrlParam.js文件的getUrlParam方法获取商品id
            var id = $.getUrlParam("id");
            console.log("id=" + id);
            $(document).ready(function() {
                $.ajax({
                    url: "/products/" + id + "/details",
                    type: "GET",
                    dataType: "JSON",
                    success: function(json) {
                        if (json.state == 200) {
                            console.log("title=" + json.data.title);
                            //html()方法:
                            // 假设有个标签<div id="a"></div>
                            //那么$("#a").html(<p></p>)就是给该div标签加p标签
                            //$("#a").html("我爱中国")就是给该div标签填充"我爱中国"内容
                            $("#product-title").html(json.data.title);
                            $("#product-sell-point").html(json.data.sellPoint);
                            $("#product-price").html(json.data.price);

                            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>

加入购物车

(一)创建数据库

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;

(二)创建实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Cart extends baseEntity implements Serializable {
    private Integer cid;
    private Integer uid;
    private Integer pid;
    private Long price;
    private Integer num;
}

(三)加入购物车(持久层)

1.规划sql

insert into t_cart (除了cid以外的所有字段) value (匹配的值列表);
update t_cart set num=? where cid=?
select * from t_cart where uid=? and pid=?

2.设计接口和抽象方法

    //插入数据
   Integer insert(Cart cart);
   //修改商品数量
   Integer updateNumByCid(Integer cid,Integer num,String modifiedUser, Date modifiedTime);
   //c查询购物车中的数据
    Cart findByUidAndPid(Integer uid,Integer pid);
<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 set num=#{num},modified_user=#{modifiedUser}
        ,modified_time=#{modifiedTime} where cid=#{cid}

    </update>

    <select id="findByUidAndPid" resultMap="CartEntityMap">
        select * from t_cart where uid=#{uid} and pid=#{pid}
    </select>
</mapper>

(四)加入购物车(业务层)

1.规划异常

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

即使持久层的方法参数是实体类对象,业务层的方法参数也大多不是实体类对象,因为实体类的部分属性是可以在业务层进行拼接然后封装到实体类对象中,再传给持久层(比如这里的price),这样的话就降低了前端传递数据的压力,如果该对象的所有方法都必须由前端传递过来,那么业务层方法参数可以是实体类对象(如注册用户时业务层的方法参数就是User对象)

public interface ICartService {
    //加入到购物车
    void addCart(Integer uid,Integer pid,Integer amount,String username);
}

@Service
public class CartServiceImpl implements ICartService {
    @Resource
    private CartMapper cartMapper;
    @Resource
    private ProductMapper productMapper;
    @Override
    public void addCart(Integer uid, Integer pid, Integer amount, String username) {
        Cart findCart = cartMapper.findByUidAndPid(uid, pid);

        if (findCart==null){
            Cart cart=new Cart();
            Product product = productMapper.getById(pid);
            cart.setPid(pid);
            cart.setUid(uid);
            cart.setNum(amount);
            cart.setPrice(product.getPrice());
            cart.setCreatedUser(username);
            cart.setCreatedTime(new Date());
            cart.setModifiedUser(username);
            cart.setModifiedTime(new Date());
            Integer integer = cartMapper.insert(cart);
            if (integer!=1){
                throw new InsertException("加入购物车产生异常");
            }
        }
        else {
            int oldNum=findCart.getNum();
            int newNum=oldNum+amount;
            Integer integer1 = cartMapper.updateNumByCid(findCart.getCid(), newNum, username, new Date());
            if (integer1!=1){
                throw new UpdateException("修改数量时产生异常");
            }
        }

    }
}

(五)加入购物车(控制层)

1.处理异常

2.设计请求

3.处理请求


@RestController
@RequestMapping("carts")
public class CartController extends BaseController{
    @Autowired
    private ICartService cartService;
@PostMapping("add_to_cart")
    public JsonResult<Void> addCart(Integer pid, Integer amount, HttpSession session){
    Integer getuidfromsession = getuidfromsession(session);
    String getusernamesession = getusernamesession(session);
    cartService.addCart(getuidfromsession,pid,amount,getusernamesession);
    return new JsonResult<>(ok);
}


}

(六)加入购物车(前端页面)

var user = "控件某属性值或控件文本内容或自己声明的值"
data: "username="+user

data: {
    "username": "Tom",
    "age": 18
}

$("#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("您的登录信息已经过期,请重新登录!HTTP响应码:" + xhr.status);
            location.href = "login.html";
        }
    });
});

后记
👉👉💕💕美好的一天,到此结束,下次继续努力!欲知后续,请看下回分解,写作不易,感谢大家的支持!! 🌹🌹🌹

举报

相关推荐

Redis(2)

【Redis - 2】Redis高级特性

Redis-2

0 条评论