首页>代码>SSH(Struts,Spring,Hibernate)整合开发java购物商城网站>/shop/src/cn/itcast/shop/cart/action/CartAction.java
package cn.itcast.shop.cart.action;

import org.apache.struts2.ServletActionContext;

import cn.itcast.shop.cart.vo.Cart;
import cn.itcast.shop.cart.vo.CartItem;
import cn.itcast.shop.product.service.ProductService;
import cn.itcast.shop.product.vo.Product;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 购物车的Action
 * @author 温文星
 *
 */
public class CartAction extends ActionSupport {

	//接收pid
	private Integer pid;
	//接收数量count
	private Integer count;
	//注入商品de Service
	private ProductService productService;
	
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public void setPid(Integer pid) {
		this.pid = pid;
	}

	public void setCount(Integer count) {
		this.count = count;
	}

	//将购物项添加到购物车:执行的方法
	public String addCart(){
		//封装一个CartItem对象
		CartItem cartItem = new CartItem();
		//设置数量
		cartItem.setCount(count);
		//根据pid进行查询商品
		Product product = productService.findByPid(pid);
		//设置商品
		cartItem.setProduct(product);
		//将购物项添加到购物车
		//购物车应该存在session中
		Cart cart = getCart();
		cart.addCart(cartItem);
		
		return "addCart";
	}
	
	//清空购物车的执行方法
	public String clearCart(){
		//获得购物车对象
		Cart cart = getCart();
		//调用购物车中的清空方法
		cart.clearCart();
		return "clearCart";
	}
	
	//从购物车中移除购物项的方法
	public String removeCart(){
		//获得购物车对象
		Cart cart = getCart();
		//调用购物车中移除的方法
		cart.removeCart(pid);
		//返回页面
		return "removeCart";
	}
	
	public String myCart(){
		return "myCart";
	}

	/**
	 * 获得购物车的方法:从session中获得购物车
	 * @return
	 */
	private Cart getCart() {
		Cart cart = (Cart) ServletActionContext.getRequest().getSession().getAttribute("cart");
		if(cart == null){
			cart = new Cart();
			ServletActionContext.getRequest().getSession().setAttribute("cart", cart);
		}
		return cart;
	}
}
最近下载更多
曾显示  LV6 2024年7月7日
yangyang0105  LV2 2023年11月13日
微信网友_6680567232876544  LV8 2023年10月8日
limin123  LV6 2023年6月25日
524109  LV5 2023年4月13日
17693282606  LV12 2022年7月12日
wangyunhao  LV10 2022年6月3日
978806986  LV16 2022年5月31日
lc123321  LV4 2022年4月8日
lzlzyw  LV14 2022年3月24日
最近浏览更多
YiRenHun  LV11 3月23日
orang801  LV2 2月24日
mianju 2024年12月19日
暂无贡献等级
sjwc88  LV3 2024年12月4日
玫瑰王子的共犯 2024年11月2日
暂无贡献等级
lyh1989  LV34 2024年7月19日
lyt010628  LV4 2024年7月8日
曾显示  LV6 2024年7月7日
樱花味小然子  LV5 2024年7月2日
y_x_happy  LV4 2024年6月25日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友