一.用户登录添加商品使用cookie存入购物车,并把购物车商品传入到后台
步骤1:创建购物车BO对象
public class ShopcartBO {
private String itemId;
private String itemImgUrl;
private String itemName;
private String specId;
private String specName;
private Integer buyCounts;
private String priceDiscount;
private String priceNormal;
//TODO get和set方法
}
步骤2:创建controller接口购物车数据
@Api(value = "购物车接口controller", tags = {"购物车接口相关的api"})
@RequestMapping("shopcart")
@RestController
public class ShopCatController {
@ApiOperation(value = "添加商品到购物车", notes = "添加商品到购物车", httpMethod = "POST")
@PostMapping("/add")
public JSONResult add(@RequestParam String userId, @RequestBody ShopcartBO shopcartBO, HttpServletRequest request, HttpServletResponse response) {
//判断用户id是否为空
if (StringUtils.isBlank(userId)) {return JSONResult.errorMsg("");}
System.out.println(shopcartBO);
// TODO 前端用户在登录的情况下,添加商品到购物车,会同时在后端同步购物车到redis缓存
return JSONResult.ok();
}
}
二.根据用户购物车商品请求后台获取最新商品的价格到购物车页面
步骤1:创建购物车VO信息
public class ShopcartVO {
private String itemId;
private String itemImgUrl;
private String itemName;
private String specId;
private String specName;
private String priceDiscount;
private String priceNormal;;
}
步骤2:对应mapper.xml中根据商品规格查询对应购物车VO信息
<select id="queryItemsBySpecIds" parameterType="List" resultType="com.imooc.pojo.vo.ShopcartVO">
SELECT
t_items.id as itemId,
t_items.item_name as itemName,
t_items_img.url as itemImgUrl,
t_items_spec.id as specId,
t_items_spec.`name` as specName,
t_items_spec.price_discount as priceDiscount,
t_items_spec.price_normal as priceNormal
FROM
items_spec t_items_spec
LEFT JOIN
items t_items
ON
t_items.id = t_items_spec.item_id
LEFT JOIN
items_img t_items_img
on
t_items_img.item_id = t_items.id
WHERE
t_items_img.is_main = 1
AND
t_items_spec.id IN
<foreach collection="paramsList" index="index" item="specId" open="(" separator="," close=")">
#{specId}
</foreach>
</select>
步骤3:写mapper对应接口方法
public List queryItemsBySpecIds(@Param(“paramsList”) List specIdsList);
步骤4:创建service接口和实现类
/**
* 根据规格ids查询最新的购物车中商品数据(用于刷新渲染购物车中的商品数据)
* @param specIds
* @return
*/
public List<ShopcartVO> queryItemsBySpecIds(String specIds);
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public List<ShopcartVO> queryItemsBySpecIds(String specIds) {
String ids[] = specIds.split(",");
List<String> specIdsList = new ArrayList<>();
Collections.addAll(specIdsList, ids);
return itemsMapperCustom.queryItemsBySpecIds(specIdsList);
}
步骤5:编写controller控制访问层
// 用于用户长时间未登录网站,刷新购物车中的数据(主要是商品价格)
@ApiOperation(value = "根据商品规格ids查找最新的商品数据", notes = "根据商品规格ids查找最新的商品数据", httpMethod = "GET")
@GetMapping("/refresh")
public JSONResult refresh(
@ApiParam(name = "itemSpecIds", value = "拼接的规格ids", required = true, example = "1001,1003,1005")
@RequestParam String itemSpecIds) {
if (StringUtils.isBlank(itemSpecIds)) {
return JSONResult.ok();
}
List<ShopcartVO> list = itemService.queryItemsBySpecIds(itemSpecIds);
return JSONResult.ok(list);
}