✅P245_商城业务-购物车-选中购物项
大约 1 分钟
实现效果
取消选中,总价会随之改变
页面修改
cfmall-cart/src/main/resources/templates/cartList.html
为input框设置class方便后续绑定单击事件修改选中状态,自定义属性保存skuId
单击事件编写 ,prop会返回true或false
$(".itemCheck").click(function () {
const skuId = $(this).attr("skuId");
const checked = $(this).prop("checked");
location.href = "http://cart.cfmall.com/checkItem?skuId=" + skuId + "&checked=" + (checked ? 1 : 0);
});
业务实现
Controller
cfmall-cart/src/main/java/com/gyz/cfmall/controller/CartController.java
/**
* 商品是否选中
*
* @param skuId
* @param checked
* @return
*/
@GetMapping(value = "/checkItem")
public String checkItem(@RequestParam(value = "skuId") Long skuId,
@RequestParam(value = "checked") Integer checked) {
cartService.checkItem(skuId, checked);
return "redirect:http://cart.cfmall.com/cart.html";
}
Service
com.gyz.cfmall.service.impl.CartServiceImpl#checkItem
@Override
public void checkItem(Long skuId, Integer checked) {
//获取单个商品
CartItemVo cartItem = this.getCartItem(skuId);
//修改商品状态
cartItem.setCheck(checked == 1 ? true : false);
//序列化存入redis中
String redisValue = JSON.toJSONString(cartItem);
BoundHashOperations<String, Object, Object> cartOps = this.getCartOpts();
cartOps.put(skuId.toString(), redisValue);
}
com.gyz.cfmall.service.impl.CartServiceImpl#getCartItem
@Override
public CartItemVo getCartItem(Long skuId) {
//拿到要操作的购物车信息
BoundHashOperations<String, Object, Object> cartOps = getCartOpts();
String redisValue = (String) cartOps.get(skuId.toString());
CartItemVo cartItemVo = JSON.parseObject(redisValue, CartItemVo.class);
return cartItemVo;
}
com.gyz.cfmall.service.impl.CartServiceImpl#getCartOpts
@Resource
private StringRedisTemplate stringRedisTemplate;
private BoundHashOperations<String, Object, Object> getCartOpts() {
UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
String cartKey;
if (userInfoTo.getUserId() != null) {
cartKey = CART_PREFIX + userInfoTo.getUserId();
} else {
cartKey = CART_PREFIX + userInfoTo.getUserKey();
}
BoundHashOperations<String, Object, Object> boundHashOps = stringRedisTemplate.boundHashOps(cartKey);
return boundHashOps;
}