您的位置:首页 > 其它

SSM综合项目实战(TTSC) -- day12 购物车

2017-10-29 16:31 531 查看

一、购物车的流程

1、以前的购物车流程



存在的问题:

(1)、购物车保存在session,如果session销毁,购物车就没了

        给购物车做持久化操作

(2)、用户未登录的时候,不能添加购物车

        未登录状态,可以把购物车数据保存在cookie

(3)、购物车使用session,session是使用服务器的内存,使用了服务器的内存资源,这样很不好

        MySQL数据库(数据的完整性)

        redis数据库(使用redis,I/O读写速度快)

(4)、session无法共享,无法行水平扩展(集群)

2、现在的购物车个流程



二、购物车系统的搭建

1、购物车系统在架构中的位置



2、创建聚合父工程taotao-cart





3、创建父工程的子工程taotao-cart-interface、taotao-cart-service













4、加入依赖关系

taotao-cart-interface            依赖           taotao-manager-pojo

taotao-cart-service              依赖           taotao-manager-mapper、taotao-cart-interface

5、加入tomcat插件



6、将taotao-manager-service的配置文件拷入,并改造







7、将taotao-manager-service中的redis配置拷入



三、搭建购物车功能的代码环境

1、创建购物车的pojo类



package com.taotao.manager.pojo;

/**
* 购物车的pojo
*
* @author Administrator
*
*/
public class Cart extends BasePojo {

private Long id;
private Long userId;
private Long itemId;
private String itemTitle;
private String itemImage;
private Long itemPrice;
private Integer num;

public Cart(Long id, Long userId, Long itemId, String itemTitle, String itemImage, Long itemPrice, Integer num) {
super();
this.id = id;
this.userId = userId;
this.itemId = itemId;
this.itemTitle = itemTitle;
this.itemImage = itemImage;
this.itemPrice = itemPrice;
this.num = num;
}

public Cart() {
super();
// TODO Auto-generated constructor stub
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public Long getUserId() {
return userId;
}

public void setUserId(Long userId) {
this.userId = userId;
}

public Long getItemId() {
return itemId;
}

public void setItemId(Long itemId) {
this.itemId = itemId;
}

public String getItemTitle() {
return itemTitle;
}

public void setItemTitle(String itemTitle) {
this.itemTitle = itemTitle;
}

public String getItemImage() {
return itemImage;
}

public void setItemImage(String itemImage) {
this.itemImage = itemImage;
}

public Long getItemPrice() {
return itemPrice;
}

public void setItemPrice(Long itemPrice) {
this.itemPrice = itemPrice;
}

public Integer getNum() {
return num;
}

public void setNum(Integer num) {
this.num = num;
}

@Override
public String toString() {
return "Cart [id=" + id + ", userId=" + userId + ", itemId=" + itemId + ", itemTitle=" + itemTitle
+ ", itemImage=" + itemImage + ", itemPrice=" + itemPrice + ", num=" + num + "]";
}

}


2、创建购物车的Service层接口和实现类

package com.taotao.cart.service;

/**
* 购物车的业务层接口
* @author Administrator
*
*/
public interface CartService {

}

package com.taotao.cart.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.cart.redis.RedisUtils;
import com.taotao.cart.service.CartService;

/**
* 购物车的业务层实现类
*
* @author Administrator
*
*/
@Service
public class CartServiceImpl implements CartService {

@Autowired
private RedisUtils redisUtils;
}


3、在taotao-cart-service中声明服务的发布



4、在taotao-portal加入对taotao-cart-interface的依赖并在spring.xml中声明服务的调用



5、创建表现层的CarController



四、购物车功能分析

1、商品详情页面添加购物车按钮分析及改造





2、需求分析

用户进入商品详情页可以点击“加入购物车”按钮,然后跳转到购物车详情页,可以查看到新添加的商品和之前添加的商品

首先完成登录状态下的购物车功能

实现需要完成两件事:

(1)、添加商品到购物车

        获取用户信息 调用购物车服务,把商品数据保存在redis的购物车中的

        参数包含:用户id,商品id,商品数量

(2)、展示购物车详情页

        获取用户信息,需要用户的id

        调用购物车服务,把该用户的所有购物车数据查询数来,根据用户id查询

        跳转到购物车页面(cart.jsp),显示数据

前台系统实现的购物车功能,所以在前台系统的controller接受请求前台系统调用购物车服务,实现把商品添加到购物车中

五、实现登录状态的购物车功能

1、在静态资源文件中添加内容



2、编写Controlelr层代码



package com.taotao.portal.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.taotao.cart.service.CartService;
import com.taotao.manager.pojo.Cart;
import com.taotao.manager.pojo.User;
import com.taotao.portal.utils.CookieUtils;
import com.taotao.sso.service.UserService;

/**
* 购物侧的表现层
*
* @author Administrator
*
*/
@Controller
@RequestMapping("cart")
public class CartController {

@Autowired
private CartService cartService;

@Autowired
private UserService userService;

@Value("${COOKIE_TICKET}")
private String COOKIE_TICKET;

/**
* 添加商品到购物车
*
* @param request
* @param itemId
* @param num
* @return
*/
@RequestMapping(value = "{itemId}", method = RequestMethod.GET)
public String addItemByCart(HttpServletRequest request, @PathVariable Long itemId, Integer num) {
// 从cookie中获取用户登录信息
User user = this.getUserByTicket(request);
// 判断用户是否登录
if (user != null) {
// 如果为不为null
// 用户登录状态下添加购物车
// 根据用户id查询购物车信息,把商品合并到购物车中
this.cartService.addItemByCart(user.getId(), itemId, num);
} else {
// 如果为null,表示用户为登录

}
return "redirect:/cart/show.html";
}

/**
* 从cookie中获取用户登录的信息
*
* @param request
*/
private User getUserByTicket(HttpServletRequest request) {
// 从cookie中获取ticket
String ticket = CookieUtils.getCookieValue(request, this.COOKIE_TICKET, true);
// 调用单点登录服务,根据ticket查询用户登录信息
User user = this.userService.queryUserByTicket(ticket);
return user;
}

/**
* 展示购物车详情页面
*
* @return
*/
@RequestMapping(value = "show", method = RequestMethod.GET)
public String show(HttpServletRequest request, Model model) {
// 从cookie中获取用户登录信息
User user = this.getUserByTicket(request);
List<Cart> cartList = null;
// 判断用户是否为null
if (user != null) {
// 不为null表示用户已经登录
// 根据用户id查询购物车信息
cartList = this.cartService.queryCartByUserId(user.getId());
} else {
// 如果为null,表示用户未登录
}

// 把查询到的购物车列表传递给页面用于展示
model.addAttribute("cartList", cartList);
return "cart";
}

}


3、编写service层接口和实现类



package com.taotao.cart.service;

import java.util.List;

import com.taotao.manager.pojo.Cart;

/**
* 购物车的业务层接口
*
* @author Administrator
*
*/
public interface CartService {

/**
* 添加商品到购物车中
*
* @param id
* @param itemId
* @param num
*/
public void addItemByCart(Long id, Long itemId, Integer num);

/**
* 根据用户id查询购物车列表
*
* @param id
* @return
*/
public List<Cart> queryCartByUserId(Long id);

}

package com.taotao.cart.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.cart.redis.RedisUtils;
import com.taotao.cart.service.CartService;
import com.taotao.manager.mapper.ItemMapper;
import com.taotao.manager.pojo.Cart;
import com.taotao.manager.pojo.Item;

/**
* 购物车的业务层实现类
*
* @author Administrator
*
*/
@Service
public class CartServiceImpl implements CartService {

private static final ObjectMapper MAPPER = new ObjectMapper();

@Autowired
private RedisUtils redisUtils;

@Value("${TAOTAO_CART_KEY_PRE}")
private String TAOTAO_CART_KEY_PRE;

@Autowired
private ItemMapper itemMapper;

public void addItemByCart(Long userId, Long itemId, Integer num) {
// 根据用户id查询购物车
List<Cart> cartList = this.queryCartByUserId(userId);
// 遍历购物车,判断购物车中是否存在该商品
Cart cart = null;
for (Cart c : cartList) {
// 判断购物车中是否存在该商品
if (c.getItemId().longValue() == itemId.longValue()) {
// 购物车中存在该商品
cart = c;
// 跳出循环
break;
}
}
if (cart != null) {
// 如果购物车中存在商品,则商品数量相加
cart.setNum(cart.getNum() + num);
cart.setUpdated(new Date());
} else {
// 如果购物车中不存在商品,则把商品添加到购物车中
// 根据id查询商品数据
Item item = this.itemMapper.selectByPrimaryKey(itemId);
// 创建购物车
cart = new Cart();
// 设置购物车数据
cart.setUserId(userId);
cart.setItemId(itemId);
cart.setNum(num);
if (null == item.getImages()) {
cart.setItemImage("");
} else {
cart.setItemImage(item.getImages()[0]);
}
cart.setItemPrice(item.getPrice());
cart.setItemTitle(item.getTitle());
cart.setCreated(new Date());
cart.setUpdated(cart.getCreated());

// 把购物车添加到list集合中
cartList.add(cart);

}
try {
// 把修改后的购物车信息放到redis中
this.redisUtils.set(this.TAOTAO_CART_KEY_PRE + userId, MAPPER.writeValueAsString(cartList));
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public List<Cart> queryCartByUserId(Long userId) {
// 根据用户id查询redis中的购物车信息
String jsonCart = this.redisUtils.get(this.TAOTAO_CART_KEY_PRE + userId);
// 判断json数据是否为null
if (StringUtils.isNotBlank(jsonCart)) {
try {
// 解析json数据
List<Cart> list = MAPPER.readValue(jsonCart,
MAPPER.getTypeFactory().constructCollectionType(List.class, Cart.class));
return list;
} catch (Exception e) {
e.printStackTrace();
}
}
return new ArrayList<Cart>();
}
}


4、测试运行添加到购物车效果



5、实现在登录状态下购物车界面修改商品数量功能

(1)、分析页面商品数量加减号点击事件





(2)、编写CartController中修改商品数量的方法

/**
* 购物车页面根据商品id修改商品数量
*
* @param request
* @param itemId
* @param num
*/
@RequestMapping(value = "update/num/{itemId}/{num}", method = RequestMethod.POST)
@ResponseBody
public void updateItemByCart(HttpServletRequest request, @PathVariable Long itemId, @PathVariable Integer num) {
// 从cookie中获取当前用户登录信息
String ticket = CookieUtils.getCookieValue(request, this.COOKIE_TICKET);
// 调用方法,根据ticket获取用户信息
User user = this.userService.queryUserByTicket(ticket);
// 判断用户是否登录
if (user != null) {
// 用户已经登录
// 调用方法更新购物车信息
this.cartService.updateItemByCart(user.getId(), itemId, num);
//
} else {
// 用户未登录
}
}


(3)、编写Service层接口和实现类

/**
* 修改购物车商品数量
*
* @param userId
* @param itemId
* @param num
*/
public void updateItemByCart(Long userId, Long itemId, Integer num);

/**
* 修改购物车商品数量
*/
public void updateItemByCart(Long userId, Long itemId, Integer num) {
// 根据用户id查询购物车信息
List<Cart> cartList = this.queryCartByUserId(userId);
// 遍历购物车信息
for (Cart cart : cartList) {
// 判断购物车中是否存在该商品
if (cart.getItemId().longValue() == itemId.longValue()) {
// 存在该商品,修改商品数量
cart.setNum(num);
cart.setUpdated(new Date());
try {
// 把修改后的商品数据放到redis中
this.redisUtils.set(this.TAOTAO_CART_KEY_PRE + userId, MAPPER.writeValueAsString(cartList));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 跳出循环
break;
}
}

}


6、实现登录状态下的删除购物车中商品操作

(1)、Controller层代码

/**
* 删除购物车中的商品
*
* @param request
* @param itemId
* @return
*/
@RequestMapping(value = "delete/{itemId}", method = RequestMethod.GET)
public String deleteItemByCart(HttpServletRequest request, @PathVariable Long itemId) {
// 从cookie中获取用户ticket
String ticket = CookieUtils.getCookieValue(request, this.COOKIE_TICKET);
// 调用方法,根据ticket获取用户信息
User user = this.userService.queryUserByTicket(ticket);
// 判断用户是否为null
if (user != null) {
// 用户已经登录
this.cartService.deleteItemByCart(user.getId(), itemId);
} else {
// 用户未登录
}
return "redirect:/cart/show.html";
}


(2)、Service层接口和实现类

/**
* 删除购物车中的商品
*
* @param id
* @param itemId
*/
public void deleteItemByCart(Long id, Long itemId);

/**
* 删除购物车中的商品
*/
public void deleteItemByCart(Long userId, Long itemId) {
// 根据用户信息,查询出购物车列表
List<Cart> cartList = this.queryCartByUserId(userId);
// 遍历购物车
for (Cart cart : cartList) {
// 判断商品是否存在
if (cart.getItemId().longValue() == itemId.longValue()) {
// 存在,则删除商品
cartList.remove(cart);
try {
// 将数据从新写回到redis中
this.redisUtils.set(this.TAOTAO_CART_KEY_PRE + userId, MAPPER.writeValueAsString(cartList));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// 跳出循环
break;
}

}
}


六、实现未登录状态的购物车功能

1、修改spring.xml中扫描注解的路径,并添加商品服务的调用



2、在资源文件中添加cookie中存放购物车的key



3、修改未登录状态下添加购物车和展示购物车信息的代码

(1)、Controlelr层



(2)、Service层



package com.taotao.portal.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.manager.pojo.Cart;
import com.taotao.manager.pojo.Item;
import com.taotao.manager.service.ItemService;
import com.taotao.portal.utils.CookieUtils;

/**
* 从cookie中操作购物车信息的业务层方法
* @author Administrator
*
*/
@Service
public class CartCookieService {

private static final ObjectMapper MAPPER = new ObjectMapper();

@Value("${TAOTAO_COOKIE_CART}")
private String TAOTAO_COOKIE_CART;

@Autowired
private ItemService itemService;

/**
* 未登录状态下将商品添加到购物成中的操作
*
* @param request
* @param response
* @param itemId
* @param num
*/
public void addItemByCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num) {
// 查询cookie中的购物车数据
List<Cart> cartList = this.queryCartByCookie(request);

// 遍历购物车
Cart cart = null;
for (Cart c : cartList) {
// 判断商品是否存在
if (c.getItemId().longValue() == itemId.longValue()) {
cart = c;
// 跳出循环
break;
}
}
// 判断Cookie中的购物车是否存在
if (cart != null) {
// 购物车存在,把商品数量添加
cart.setNum(cart.getNum() + num);
cart.setUpdated(new Date());
} else {
// 购物车不存在,新增商品
// 根据id查询商品数据
Item item = this.itemService.queryById(itemId);
// 创建购物车,封装数据
cart = new Cart();

cart.setItemId(itemId);
cart.setNum(num);
if (item.getImages() != null && item.getImages().length > 0) {
cart.setItemImage(item.getImages()[0]);
} else {
cart.setItemImage("");
}
cart.setItemPrice(item.getPrice());
cart.setItemTitle(item.getTitle());
cart.setCreated(new Date());
cart.setUpdated(item.getCreated());
// 把封装好的商品数据放到购物车中
cartList.add(cart);
}
try {
// 把修改后的购物车信息放到cookie中
CookieUtils.setCookie(request, response, this.TAOTAO_COOKIE_CART, MAPPER.writeValueAsString(cartList),
60 * 60 * 24, true);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 查询cookie中的购物车
*
* @param request
* @return
*/
public List<Cart> queryCartByCookie(HttpServletRequest request) {
// 查询cookie中的购物车数据
String jsonCart = CookieUtils.getCookieValue(request, this.TAOTAO_COOKIE_CART, true);
// 判断数据是否为空
if (StringUtils.isNotBlank(jsonCart)) {
try {
// 不为空,则解析为购物车
List<Cart> list = MAPPER.readValue(jsonCart,
MAPPER.getTypeFactory().constructCollectionType(List.class, Cart.class));
// 返回购物车数据
return list;
} catch (Exception e) {
e.printStackTrace();
}
}
return new ArrayList<Cart>();
}

}

4、实现未登录状态下修改购物车中商品数量和删除购物车信息

(1)、修改CartController中代码



(2)、添加cartCookieService中的方法

/**
* 更新Cookie中购物车中商品数量
*
* @param request
* @param response
* @param itemId
* @param num
*/
public void updateItemByCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num) {
// 从cookie中获取购物车列表
List<Cart> cartList = this.queryCartByCookie(request);
for (Cart cart : cartList) {
if (cart.getItemId().longValue() == itemId.longValue()) {
// 修改商品数量
cart.setNum(num);
cart.setUpdated(new Date());

try {
// 把修改后的购物车信息放到cookie中
CookieUtils.setCookie(request, response, this.TAOTAO_COOKIE_CART,
MAPPER.writeValueAsString(cartList), 60 * 60 * 24, true);
} catch (Exception e) {
e.printStackTrace();
}
// 跳出循环
break;
}
}
}

/**
* 删除cookie中购物车信息
*
* @param request
* @param response
* @param itemId
*/
public void deleteItemByCart(HttpServletRequest request, HttpServletResponse response, Long itemId) {

// 从cookie中获取购物车信息
List<Cart> cartList = this.queryCartByCookie(request);
// 遍历购物车列表
for (Cart cart : cartList) {
if (cart.getItemId().longValue() == itemId.longValue()) {
// 删除商品信息
cartList.remove(cart);
// 保存购物车信息
try {
// 把修改后的购物车信息放到cookie中
CookieUtils.setCookie(request, response, this.TAOTAO_COOKIE_CART,
MAPPER.writeValueAsString(cartList), 60 * 60 * 24, true);
} catch (Exception e) {
e.printStackTrace();
}
// 跳出循环
break;
}
}
}

七、购物车整体总结

1、流程分析

未登录

已登陆

2、Controller层代码

package com.taotao.portal.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.cart.service.CartService;
import com.taotao.manager.pojo.Cart;
import com.taotao.manager.pojo.User;
import com.taotao.portal.service.CartCookieService;
import com.taotao.portal.utils.CookieUtils;
import com.taotao.sso.service.UserService;

/**
* 购物侧的表现层
*
* @author Administrator
*
*/
@Controller
@RequestMapping("cart")
public class CartController {

@Autowired
private CartService cartService;

@Autowired
private UserService userService;

@Value("${COOKIE_TICKET}")
private String COOKIE_TICKET;

@Autowired
private CartCookieService cartCookieService;

/**
* 添加商品到购物车
*
* @param request
* @param itemId
* @param num
* @return
*/
@RequestMapping(value = "{itemId}", method = RequestMethod.GET)
public String addItemByCart(HttpServletRequest request, HttpServletResponse response, @PathVariable Long itemId,
Integer num) {
// 从cookie中获取用户登录信息
User user = this.getUserByTicket(request);
// 判断用户是否登录
if (user != null) {
// 如果为不为null
// 用户登录状态下添加购物车
// 根据用户id查询购物车信息,把商品合并到购物车中
this.cartService.addItemByCart(user.getId(), itemId, num);
} else {
// 如果为null,表示用户未登录
this.cartCookieService.addItemByCart(request, response, itemId, num);
}
return "redirect:/cart/show.html";
}

/**
* 从cookie中获取用户登录的信息
*
* @param request
*/
private User getUserByTicket(HttpServletRequest request) {
// 从cookie中获取ticket
String ticket = CookieUtils.getCookieValue(request, this.COOKIE_TICKET, true);
// 调用单点登录服务,根据ticket查询用户登录信息
User user = this.userService.queryUserByTicket(ticket);
return user;
}

/**
* 展示购物车详情页面
*
* @return
*/
@RequestMapping(value = "show", method = RequestMethod.GET)
public String show(HttpServletRequest request, Model model) {
// 从cookie中获取用户登录信息
User user = this.getUserByTicket(request);
List<Cart> cartList = null;
// 判断用户是否为null
if (user != null) {
// 不为null表示用户已经登录
// 根据用户id查询购物车信息
cartList = this.cartService.queryCartByUserId(user.getId());
} else {
// 如果为null,表示用户未登录
// 从cookie中查询用户购物车信息
cartList = this.cartCookieService.queryCartByCookie(request);
}

// 把查询到的购物车列表传递给页面用于展示
model.addAttribute("cartList", cartList);
return "cart";
}

/**
* 购物车页面根据商品id修改商品数量
*
* @param request
* @param itemId
* @param num
*/
@RequestMapping(value = "update/num/{itemId}/{num}", method = RequestMethod.POST)
@ResponseBody
public void updateItemByCart(HttpServletRequest request, HttpServletResponse response, @PathVariable Long itemId,
@PathVariable Integer num) {
// 从cookie中获取当前用户登录信息
String ticket = CookieUtils.getCookieValue(request, this.COOKIE_TICKET);
// 调用方法,根据ticket获取用户信息
User user = this.userService.queryUserByTicket(ticket);
// 判断用户是否登录
if (user != null) {
// 用户已经登录
// 调用方法更新购物车信息
this.cartService.updateItemByCart(user.getId(), itemId, num);
} else {
// 用户未登录
// 调用方法更新数据
this.cartCookieService.updateItemByCart(request, response, itemId, num);
}
}

/**
* 删除购物车中的商品
*
* @param request
* @param itemId
* @return
*/
@RequestMapping(value = "delete/{itemId}", method = RequestMethod.GET)
public String deleteItemByCart(HttpServletRequest request, HttpServletResponse response,
@PathVariable Long itemId) {
// 从cookie中获取用户ticket
String ticket = CookieUtils.getCookieValue(request, this.COOKIE_TICKET);
// 调用方法,根据ticket获取用户信息
User user = this.userService.queryUserByTicket(ticket);
// 判断用户是否为null
if (user != null) {
// 用户已经登录
this.cartService.deleteItemByCart(user.getId(), itemId);
} else {
// 用户未登录
this.cartCookieService.deleteItemByCart(request,response,itemId);
}
return "redirect:/cart/show.html";
}

}

3、Service层接口和实现类

(1)、cartService接口和实现类

cartService.java

package com.taotao.cart.service;

import java.util.List;

import com.taotao.manager.pojo.Cart;

/**
* 购物车的业务层接口
*
* @author Administrator
*
*/
public interface CartService {

/**
* 添加商品到购物车中
*
* @param id
* @param itemId
* @param num
*/
public void addItemByCart(Long id, Long itemId, Integer num);

/**
* 根据用户id查询购物车列表
*
* @param id
* @return
*/
public List<Cart> queryCartByUserId(Long id);

/**
* 修改购物车商品数量
*
* @param userId
* @param itemId
* @param num
*/
public void updateItemByCart(Long userId, Long itemId, Integer num);

/**
* 删除购物车中的商品
*
* @param id
* @param itemId
*/
public void deleteItemByCart(Long id, Long itemId);

}

CartServiceImpl.java

package com.taotao.cart.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.cart.redis.RedisUtils;
import com.taotao.cart.service.CartService;
import com.taotao.manager.mapper.ItemMapper;
import com.taotao.manager.pojo.Cart;
import com.taotao.manager.pojo.Item;

/**
* 购物车的业务层实现类
*
* @author Administrator
*
*/
@Service
public class CartServiceImpl implements CartService {

private static final ObjectMapper MAPPER = new ObjectMapper();

@Autowired
private RedisUtils redisUtils;

@Value("${TAOTAO_CART_KEY_PRE}")
private String TAOTAO_CART_KEY_PRE;

@Autowired
private ItemMapper itemMapper;

public void addItemByCart(Long userId, Long itemId, Integer num) {
// 根据用户id查询购物车
List<Cart> cartList = this.queryCartByUserId(userId);
// 遍历购物车,判断购物车中是否存在该商品
Cart cart = null;
for (Cart c : cartList) {
// 判断购物车中是否存在该商品
if (c.getItemId().longValue() == itemId.longValue()) {
// 购物车中存在该商品
cart = c;
// 跳出循环
break;
}
}
if (cart != null) {
// 如果购物车中存在商品,则商品数量相加
cart.setNum(cart.getNum() + num);
cart.setUpdated(new Date());
} else {
// 如果购物车中不存在商品,则把商品添加到购物车中
// 根据id查询商品数据
Item item = this.itemMapper.selectByPrimaryKey(itemId);
// 创建购物车
cart = new Cart();
// 设置购物车数据
cart.setUserId(userId);
cart.setItemId(itemId);
cart.setNum(num);
if (null == item.getImages()) {
cart.setItemImage("");
} else {
cart.setItemImage(item.getImages()[0]);
}
cart.setItemPrice(item.getPrice());
cart.setItemTitle(item.getTitle());
cart.setCreated(new Date());
cart.setUpdated(cart.getCreated());

// 把购物车添加到list集合中
cartList.add(cart);

}
try {
// 把修改后的购物车信息放到redis中
this.redisUtils.set(this.TAOTAO_CART_KEY_PRE + userId, MAPPER.writeValueAsString(cartList));
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public List<Cart> queryCartByUserId(Long userId) {
// 根据用户id查询redis中的购物车信息
String jsonCart = this.redisUtils.get(this.TAOTAO_CART_KEY_PRE + userId);
// 判断json数据是否为null
if (StringUtils.isNotBlank(jsonCart)) {
try {
// 解析json数据
List<Cart> list = MAPPER.readValue(jsonCart,
MAPPER.getTypeFactory().constructCollectionType(List.class, Cart.class));
return list;
} catch (Exception e) {
e.printStackTrace();
}
}
return new ArrayList<Cart>();
}

/**
* 修改购物车商品数量
*/
public void updateItemByCart(Long userId, Long itemId, Integer num) {
// 根据用户id查询购物车信息
List<Cart> cartList = this.queryCartByUserId(userId);
// 遍历购物车信息
for (Cart cart : cartList) {
// 判断购物车中是否存在该商品
if (cart.getItemId().longValue() == itemId.longValue()) {
// 存在该商品,修改商品数量
cart.setNum(num);
cart.setUpdated(new Date());
try {
// 把修改后的商品数据放到redis中
this.redisUtils.set(this.TAOTAO_CART_KEY_PRE + userId, MAPPER.writeValueAsString(cartList));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 跳出循环
break;
}
}

}

/**
* 删除购物车中的商品
*/
public void deleteItemByCart(Long userId, Long itemId) {
// 根据用户信息,查询出购物车列表
List<Cart> cartList = this.queryCartByUserId(userId);
// 遍历购物车
for (Cart cart : cartList) {
// 判断商品是否存在
if (cart.getItemId().longValue() == itemId.longValue()) {
// 存在,则删除商品
cartList.remove(cart);
try {
// 将数据从新写回到redis中
this.redisUtils.set(this.TAOTAO_CART_KEY_PRE + userId, MAPPER.writeValueAsString(cartList));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// 跳出循环
break;
}

}
}
}

(2)、CartCookieService代码

CartCookieService.java

package com.taotao.portal.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.manager.pojo.Cart;
import com.taotao.manager.pojo.Item;
import com.taotao.manager.service.ItemService;
import com.taotao.portal.utils.CookieUtils;

/**
* 从cookie中操作购物车信息的业务层方法
*
* @author Administrator
*
*/
@Service
public class CartCookieService {

private static final ObjectMapper MAPPER = new ObjectMapper();

@Value("${TAOTAO_COOKIE_CART}")
private String TAOTAO_COOKIE_CART;

@Autowired
private ItemService itemService;

/**
* 未登录状态下将商品添加到购物成中的操作
*
* @param request
* @param response
* @param itemId
* @param num
*/
public void addItemByCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num) {
// 查询cookie中的购物车数据
List<Cart> cartList = this.queryCartByCookie(request);

// 遍历购物车
Cart cart = null;
for (Cart c : cartList) {
// 判断商品是否存在
if (c.getItemId().longValue() == itemId.longValue()) {
cart = c;
// 跳出循环
break;
}
}
// 判断Cookie中的购物车是否存在
if (cart != null) {
// 购物车存在,把商品数量添加
cart.setNum(cart.getNum() + num);
cart.setUpdated(new Date());
} else {
// 购物车不存在,新增商品
// 根据id查询商品数据
Item item = this.itemService.queryById(itemId);
// 创建购物车,封装数据
cart = new Cart();

cart.setItemId(itemId);
cart.setNum(num);
if (item.getImages() != null && item.getImages().length > 0) {
cart.setItemImage(item.getImages()[0]);
} else {
cart.setItemImage("");
}
cart.setItemPrice(item.getPrice());
cart.setItemTitle(item.getTitle());
cart.setCreated(new Date());
cart.setUpdated(item.getCreated());
// 把封装好的商品数据放到购物车中
cartList.add(cart);
}
try {
// 把修改后的购物车信息放到cookie中
CookieUtils.setCookie(request, response, this.TAOTAO_COOKIE_CART, MAPPER.writeValueAsString(cartList),
60 * 60 * 24, true);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 查询cookie中的购物车
*
* @param request
* @return
*/
public List<Cart> queryCartByCookie(HttpServletRequest request) {
// 查询cookie中的购物车数据
String jsonCart = CookieUtils.getCookieValue(request, this.TAOTAO_COOKIE_CART, true);
// 判断数据是否为空
if (StringUtils.isNotBlank(jsonCart)) {
try {
// 不为空,则解析为购物车
List<Cart> list = MAPPER.readValue(jsonCart,
MAPPER.getTypeFactory().constructCollectionType(List.class, Cart.class));
// 返回购物车数据
return list;
} catch (Exception e) {
e.printStackTrace();
}
}
return new ArrayList<Cart>();
}

/**
* 更新Cookie中购物车中商品数量
*
* @param request
* @param response
* @param itemId
* @param num
*/
public void updateItemByCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num) {
// 从cookie中获取购物车列表
List<Cart> cartList = this.queryCartByCookie(request);
for (Cart cart : cartList) {
if (cart.getItemId().longValue() == itemId.longValue()) {
// 修改商品数量
cart.setNum(num);
cart.setUpdated(new Date());

try {
// 把修改后的购物车信息放到cookie中
CookieUtils.setCookie(request, response, this.TAOTAO_COOKIE_CART,
MAPPER.writeValueAsString(cartList), 60 * 60 * 24, true);
} catch (Exception e) {
e.printStackTrace();
}
// 跳出循环
break;
}
}
}

/**
* 删除cookie中购物车信息
*
* @param request
* @param response
* @param itemId
*/
public void deleteItemByCart(HttpServletRequest request, HttpServletResponse response, Long itemId) {

// 从cookie中获取购物车信息
List<Cart> cartList = this.queryCartByCookie(request);
// 遍历购物车列表
for (Cart cart : cartList) {
if (cart.getItemId().longValue() == itemId.longValue()) {
// 删除商品信息
cartList.remove(cart);
// 保存购物车信息
try {
// 把修改后的购物车信息放到cookie中
CookieUtils.setCookie(request, response, this.TAOTAO_COOKIE_CART,
MAPPER.writeValueAsString(cartList), 60 * 60 * 24, true);
} catch (Exception e) {
e.printStackTrace();
}
// 跳出循环
break;
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: