Welcome 微信登录

首页 / 软件开发 / JAVA / Spring Web Flow 2.0入门 - 用subflow实现添加商品到购物车功能

Spring Web Flow 2.0入门 - 用subflow实现添加商品到购物车功能2011-02-01 IBM 吕焱飞商品已经有列表了,接下来就要增加把商品放入购物车的功能,在本示例中用 subflow 来实现这一功能,操作步骤如下:

实现 Cart 和 CartItem 两个业务类

在 shopping.xml 中添加配置

在 /WEB-INF/flows 目录下添加 addToCart.xml

在 webflow-config.xml 中添加 addToCart.xml 的位置

修改 viewCart.jsp 页面

实现 Cart 和 CartItem 两个业务类

CartItem 表示存放于购物车中的条目,主要记录相应商品及商品数量,同时不要忘记实现 java.io.Serializable 接口,见清单 29:

清单 29 CartItem 类

package samples.webflow;
import java.io.Serializable;
public class CartItem implements Serializable {
private static final long serialVersionUID = 8388627124326126637L;
private Product product;
private int quantity;
public CartItem(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public int getTotalPrice() {
return this.quantity * this.product.getPrice();
}
public void increaseQuantity() {
this.quantity++;
}
/*省略getter和setter*/
}

除去相应的属性外, CartItem 可根据商品的数量算出该商品的总价格( getTotalPrice ),也可通过 increaseQuantity 增加商品数量。

Cart 是购物车的实现类,其同样要实现 java.io.Serializable 接口,但它没有像 ProductService 一样成为由 Spring IoC 容器管理的 Bean ,每个客户的购物车是不同的,因此不能使用 Spring IoC 容器默认的 Singleton 模式。见清单 30:

清单 30 Cart 类

package samples.webflow;
/* 省略 import 语句 */
public class Cart implements Serializable {
private static final long serialVersionUID = 7901330827203016310L;
private Map<Integer, CartItem> map = new HashMap<Integer, CartItem>();
public List<CartItem> getItems() {
return new ArrayList<CartItem>(map.values());
}
public void addItem(Product product) {
int id = product.getId();
CartItem item = map.get(id);
if (item != null)
item.increaseQuantity();
else
map.put(id, new CartItem(product, 1));
}
public int getTotalPrice() {
int total = 0;
for (CartItem item : map.values())
total += item.getProduct().getPrice() * item.getQuantity();
return total;
}
}

Cart 主要实现三个业务函数, getItems 用于获取当前购物车里的物品, addItem 用于向购物车添加商品, getTotalPrice 用于获取购物车里所有商品的总价格。