欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

购物车逻辑实现 Session缓存

程序员文章站 2024-03-20 13:17:10
...
package com.offcn.easybuy.controller;

import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.offcn.easybuy.mapper.ProductMapper;
import com.offcn.easybuy.pojo.Address;
import com.offcn.easybuy.pojo.CarItem;
import com.offcn.easybuy.pojo.Cart;
import com.offcn.easybuy.pojo.Order;
import com.offcn.easybuy.pojo.Product;
import com.offcn.easybuy.pojo.User;
import com.offcn.easybuy.service.IAddressService;
import com.offcn.easybuy.service.IOrderService;
import com.offcn.easybuy.service.IProductService;


@Controller
@RequestMapping("/car")
public class ShoppingCartController {
	@Resource
	private IProductService productService;
	@Resource
	private IAddressService addressService;
	@Resource
	private IOrderService orderService;
	
	//购物车
	@RequestMapping("/add")
	@ResponseBody
	public String add(int entityId,int quantity,HttpSession session) {
		//通过主键id找到具体商品
		Product product = productService.findProductById(entityId);
		//获取购物车值
		Cart cart = getCartFromSession(session);
		String carItem = cart.addCarItem(product, entityId, quantity);
		session.setAttribute("cart", cart);
		cart.calculateTotalPrice();
		return "添加成功";
	}
	
	//从购物车拿值
	public Cart getCartFromSession(HttpSession session) {
		
		Cart cart = (Cart)session.getAttribute("cart");
		if(cart==null) {
			cart=new Cart();
		}
		return cart;
	}
	
	//刷新购物车
	@RequestMapping("/reflush")
	public String reflush(HttpSession session) {
		return "/common/pre/searchBar";
	}
	
	//toSettlement界面用于加载settlement1页面
	@RequestMapping("/settlement")
	public String settlement1() {
		return "/pre/settlement/settlement1";
	}
	
	//修改购物车,加或者减,
	@RequestMapping("/modifyCart")
	@ResponseBody
	public String modCart(int entityId,int quantity,HttpSession session) {
		 int quantity1=0;
		 float price=0;
		Product product = productService.findProductById(entityId);
			Cart cart = getCartFromSession(session);
			//拿到购物车项的集合
			List<CarItem> list = cart.getItems();
			//遍历购物车项
			for (CarItem carItem : list) {
				if(carItem.getProduct().getId()==entityId) {
						//quantity1是修改后的数量
						quantity1=quantity;
						//对购物车项数量重新修改
						carItem.setQuantity(quantity1);
						//每一项的小计
						price=product.getPrice()*quantity1;
						//重新设置购物车项的小计
						carItem.setPrice(price);
						break;
				}
			}
			cart.calculateTotalPrice();
			//再次把购物车放到session
			session.setAttribute("cart", cart);		
			return "true";
	}
	
	//删除购物车项
	@RequestMapping("/removeCart")
	@ResponseBody
	public String removeCart(HttpSession session,int entityId) {
		Cart cart = getCartFromSession(session);
		List<CarItem> list = cart.getItems();
		for (int i = 0; i < list.size(); i++) {
			if(list.get(i).getProduct().getId()==entityId){
				list.remove(i);
			}
		}
		//调用计算总价的方法,删除每一项需要重新计算总价
		cart.calculateTotalPrice();
		//重新将购物车放置在session中,覆盖原来的购物车
		session.setAttribute("cart", cart);	
		return "true";
		
	}
	//用户sttlement2界面遍历旧地址
	@RequestMapping("/settlement2")
	public String toSettlement2(HttpSession session,Model model) {
		
				User user = (User)session.getAttribute("userSession");		
				//通过登录后用户的id查地址,用户的id可以从session中获取
				List<Address> addressList = addressService.findAddressByUserId(user.getId());
				model.addAttribute("userAddressList", addressList);
		return "/pre/settlement/settlement2";
	}
	
	//增加购物车的订单
	@RequestMapping("/addOrder")
	public String addCarOrder(HttpSession session,String newAddress,float cost) {
		
		User user = (User)session.getAttribute("userSession");
		
		Order order=new Order();
		//用户的id可以从session中获取
		order.setUserid(user.getId());
		order.setLoginname(user.getLoginName());
		order.setUseraddress(newAddress);
		order.setCreatetime(new Date());
		order.setCost(cost);
				
		orderService.insertSelective(order);
		
		//订单号是uuid,在sql语句自动生成,,
		String regex="-";
		String uuid= order.getSerialnumber();
		String uuid1 = uuid.replaceAll(regex, "");
		order.setSerialnumber(uuid1);
		//因为生成的uuid是有-的,要去掉只能重新修改
		orderService.updateByPrimaryKeySelective(order);
		
		session.setAttribute("currentOrder", order);
		
		return "/pre/settlement/settlement3";
		
		
	}
}

实体类:

package com.offcn.easybuy.pojo;

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

//购物车类
public class Cart {
	
	//购物车项集合
	private List<CarItem> items=new ArrayList<CarItem>();
	//总价钱
	private Double totalPrice;



	public List<CarItem> getItems() {
		return items;
	}

	public void setItems(List<CarItem> items) {
		this.items = items;
	}

	public Double getTotalPrice() {
		return totalPrice;
	}

	public void setTotalPrice(Double totalPrice) {
		this.totalPrice = totalPrice;
	}
	
	
	//添加方法
	public String addCarItem(Product product,int entityId,int quantity) {		
		int quantityAdd=0;
		//购物车项目如果是空的
		if(getItems().size()==0) {
			if(quantity>product.getStock()) {
				return "添加失败";
			}		
			//往购物车项集合里添加商品
			items.add(new CarItem(product,quantity));					
			//购物车项有内容
		}else if(getItems().size()>0) {
			//有购物车项内容,就开始遍历购物车项,
			String item=null;
			for (CarItem cart1 :getItems()){
				//如果存在相同的购物车项
				if(entityId==cart1.getProduct().getId()) {
				//quantityAdd原来的基础上增加,获得购物车项已有的数量+传进来增加的数量,
					quantityAdd=cart1.getQuantity()+quantity;
					item="1";
					if(quantityAdd>cart1.getProduct().getStock()) {
						return "添加失败";
					}					
					//重新赋值,
					cart1.setQuantity(quantityAdd);					
				}				
			}
			if(item==null) {
				if(quantity>product.getStock()){
					return "库存不足";
				}
				items.add(new CarItem(product,quantity));
			}
		}
		return "添加成功";
	}	
	
	//计算总价钱
	public double calculateTotalPrice() {
			//初始化总价
		   double totalPrice=0.0;	  
	        for(CarItem cart:getItems()){
	        	totalPrice=totalPrice+cart.getQuantity()*cart.getProduct().getPrice();      	
	        }
	        this.totalPrice=totalPrice;
	        
	        return totalPrice;
		
	}
	

}