用户没有登录, 将购物车保存在cookie中!!!
ajax请求加入购物车接口,返回用户未登录时, 将购物车保存在cookie中。调用方法:saveCartsToCookie();
//将购物车保存在cookie中
function saveCartsToCookie() {
var carts;
// 尝试从cookie中取
var str = getCookie('carts');
// 如果取到,赋值 "[{"goodsId":"10","count":1}]"
if (str) {
carts = eval(str); // 将一个字符串,按照JS的方式执行
// 相当于写了这样的一段代码
//carts = [{"goodsId":"10","count":1}];
}
// 如果取不到,创建新的数组
if (!carts) {
carts = [];
}
// 遍历carts,找goodsId相同的,
var cart;
for (var i = 0; i < carts.length; i++) {
if (carts[i].goodsId == id) {
// 找到了
cart = carts[i];
break;
}
}
// 找到了,取出来,数量累加
if (cart) {
cart.count++;
} else {
// 找不到再push
carts.push({goodsId: id, count: 1});
}
console.log(carts);
setCookie('carts', JSON.stringify(carts));
};
// 保存
function setCookie(cname,cvalue){
exdays = 7; // 默认七天
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
};
// 获取
function getCookie(cname){
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
}
return "";
};
用户登录验证通过(登录接口),将cookie数据加入购物车
//cookie数据加入购物车
String[] strCookies = request.getHeader("Cookie").split(";");
String strCart = null;
for (String strCookie : strCookies){
strCookie = strCookie.trim();
if (strCookie.startsWith("carts=")){
strCart = strCookie.substring(strCookie.indexOf("=")+1);
System.out.println(strCart);
break;
}
}
if (strCart!=null){
// 将JSON格式的字符串,解析成一个对象
ObjectMapper om = new ObjectMapper();
List<Cart> carts = om.readValue(strCart, new TypeReference<List<Cart>>() { });
//数据存入数据库
for(Cart cart : carts) {
cart.setUserId(user.getId());
cartService.add(cart);
}
}
登录接口返回成功,清除cookie中的carts
// 清除cookie中的carts
document.cookie = "carts=[]; expires="+new Date(0)+"; path=/";
思考:登录成功,我们都是回到主页;如果这次要去到购物车列表,怎么实现???
创建拦截器
package com.situ.front.interceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.stmall.common.ResponseBean;
import com.situ.stmall.entity.Admin;
import com.situ.stmall.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class UserInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取登录信息
User user = (User) request.getSession().getAttribute("user");
if(user != null){
return true;
}else{
String url = request.getRequestURL().toString();
// 只适用于页面的跳转,不适合ajax异步请求, JSON
if (url.indexOf("/api/") >= 0){
// 返回json
ResponseBean result = ResponseBean.failed("用户未登录!!");
response.setContentType("application/json; charset=UTF-8");
response.getWriter().write(new ObjectMapper().writeValueAsString(result));
} else {
response.sendRedirect("/login");
}
return false;
}
}
}
配置文件(WebConfig)中添加注册拦截器
@Autowired
private UserInterceptor userInterceptor;
// 注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userInterceptor)
.addPathPatterns(
"/cart", //购物车
"/order", //订单
"/ok", //支付成功
"/mygxin", //个人中心
"/myorderq",//个人中心-我的订单
"/api/user/**")
.excludePathPatterns(
"/api/user/login", //登录接口
"/api/user/reg", //注册接口
"/api/user/cart" // 没登录时,也可以添加购物车
);
}