序言:
这篇文章会比较长,真正想了解的就得泡上一杯茶,慢慢阅读了!呵呵...
1.添加商品页面 add_goods.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="cartAddGoodsRequest.do" method="post">
购物(添加商品)
<br>
<table>
<tr>
<td align="right" style="width">商品ID:</td>
<td><input type="text" name="goodsId"></td>
</tr>
<tr>
<td align="right">商品所属分类:</td>
<td><input type="text" name="goodsCatalog">(填数字:0 1 2)</td>
</tr>
<tr>
<td align="right">商品价格:</td>
<td><input type="text" name="goodsPrice"></td>
</tr>
<tr>
<td align="right">购买件数:</td>
<td><input type="text" name="purchaseNumber"></td>
</tr>
<tr>
<td align="right">所属店主昵称:</td>
<td><input type="text" name="shopkeeper" ></td>
</tr>
<tr>
<td align="right">所属店铺名称:</td>
<td><input type="text" name="shop"></td>
</tr>
</table>
<input type="submit" value="提交" align="center">
</form>
</body>
</html>
说明:就是填写一些商品信息,后台是用struts处理的。至于struts的配置问题就不描述了。
2.添加商品请求由下面这个类进行处理: CartAddGoodsRequest
package cn.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import cn.struts.formbean.PurchaseGoodsBean;
/**
* 购物车添加商品请求处理类
* @author LI
*
*/
public class CartAddGoodsRequest extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("购物车添加商品处理类");
//参数对象(商品属性)
PurchaseGoodsBean pgb=(PurchaseGoodsBean)form;
System.out.println("id----"+pgb.getGoodsId()+"---shop---"+pgb.getShop());
//获得session对象
javax.servlet.http.HttpSession session=request.getSession();
//获得购物车对象
String cartString=(String)session.getAttribute("cart");
Document cartXml=null;
if(cartString!=null)
cartXml = org.dom4j.DocumentHelper.parseText(cartString);
//添加商品
Document cart=cn.netjava.utils.XMLCart.getInstance()
.addGoods(pgb, cartXml);
//购物车放入session中存放
session.setAttribute("cart", cart.asXML());
return null;
}
}
说明:1.首先从session中获得购物车对象,因为session里面存放的购物车是字符串形式(为什么,后面会讲),需要转换成Document对象 。
2.添加商品处理,这里调用的是一个叫做XMLCart类的一个addGoods方法。稍等,下面我们就来看这个类!
3.将添加了新商品的购物车重新以字符串形式保存在session当中。
3.购物车操作类(往购物车里面添加商品,修改商品数量,删除商品,清空购物车):XMLCart
package cn.netjava.utils;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import cn.struts.formbean.PurchaseGoodsBean;
/**
* XML实现的购物车
* @author LI
*
*/
public class XMLCart {
//私有构造器
private XMLCart(){};
//单实例
private static XMLCart instance=null;
//获得该实例
public static synchronized XMLCart getInstance()
{
//如果还没有被初始化
if (instance==null){
instance=new XMLCart();
}
return instance;
}
//创建购物车
public Document createCart(){
//使用DocumentHelper类创建一个文档实例,购物车对象
Document cart=DocumentHelper.createDocument();
//创建根元素cart
org.dom4j.Element cartRoot=cart.addElement("cart");
//给根节点加子节点,代表购物车总金额
Element totalMoney=cartRoot.addElement("totalMoney");
totalMoney.setText("0");
//给根节点加子节点,代表店主昵称
@SuppressWarnings("unused")
Element shopkeeper =cartRoot.addElement("shopkeeper");
//给根节点加子节点,代表店铺名称
@SuppressWarnings("unused")
Element shop =cartRoot.addElement("shop");
//商品列表
@SuppressWarnings("unused")
Element goodsList=cartRoot.addElement("goodsList");
//返回购物车对象
return cart;
}
/**
* 清空购物车
* @param cart:购物车对象
*/
public Document emptyCart(Document cart){
//获得根节点
Element root=cart.getRootElement();
//清空总资金
Element totalMoneyNode=root.element("totalMoney");
totalMoneyNode.setText(0+"");
//清空店铺和店主
Element shopNode=root.element("shop");
shopNode.setText("");
Element shopkeeperNode=root.element("shopkeeper");
shopkeeperNode.setText("");
//获得商品列表节点
Element goodsListNode=root.element("goodsList");
//遍历商品列表
java.util.List<Element>goodList=goodsListNode.elements();
for(int i=0;i<goodList.size();i++){
//得到商品节点
Element goodNode=goodList.get(i);
goodsListNode.remove(goodNode);
}
return cart;
}
/**
* 添加商品
* @param pgb:要添加的商品
* @param cart:购物车对象
*/
public Document addGoods(PurchaseGoodsBean pgb,Document cart){
//如果购物车为NULL
if(cart==null){
//新建购物车对象
cart=createCart();
}
if(pgb==null){
return cart;
}
//获得根节点
Element root=cart.getRootElement();
//判断是否为同一店铺的商品
boolean sameShop=isSameShop(pgb,cart);
//如果为不同店铺
if(!sameShop){
//清空购物车
cart=emptyCart(cart);
//设置店主昵称
Element shopkeeperNode=root.element("shopkeeper");
shopkeeperNode.setText(pgb.getShopkeeper());
//设置店铺名称
Element shopNode=root.element("shop");
shopNode.setText(pgb.getShop());
}
//判断这件商品是否已在购物车里面
boolean exist=isGoodsExist(pgb.getGoodsId(),cart);
//如果已在
if(exist){
return cart;
}else{
//添加商品
Element goodsListNode=root.element("goodsList");
Element goodsNode=goodsListNode.addElement("goods");
goodsNode.addElement("goodsId").setText(pgb.getGoodsId());
goodsNode.addElement("goodsNumber").setText(pgb.getPurchaseNumber()+"");
goodsNode.addElement("goodsCatalog").setText(pgb.getGoodsCatalog()+"");
goodsNode.addElement("goodsPrice").setText(pgb.getGoodsPrice()+"");
//操作数据库,根据商品ID获得商品的图片,名称,价格。
//这里人工生成
goodsNode.addElement("goodsPicture").setText("image/1.jpg");
goodsNode.addElement("goodsName").setText("精致MP3");
//设置商品积分
int goodsIntegral=(int) pgb.getGoodsPrice()*pgb.getPurchaseNumber();
goodsNode.addElement("goodsIntegral").setText(goodsIntegral+"");
//设置每样商品资金小计
double goodsTotalMoney=pgb.getGoodsPrice()*pgb.getPurchaseNumber();
goodsNode.addElement("goodsSubtotal").setText(goodsTotalMoney+"");
//获得当前总资金
double totalMoney=Double.parseDouble
(root.element("totalMoney").getText());
//修改总金额
double modifyTotalMoney=goodsTotalMoney+totalMoney;
root.element("totalMoney").setText(modifyTotalMoney+"");
}
System.out.println(cart.asXML());
return cart;
}
/**
* 购买的商品是否属于同一店铺
* @param pgb:购买的商品属性
* @param cart:购物车
* @return:TRUE:属于同一店铺 FALSE:不属于同一店铺
*/
public boolean isSameShop(PurchaseGoodsBean pgb,Document cart){
//获得根节点
Element root=cart.getRootElement();
//获得店主节点
Element shopkeeperNode=root.element("shopkeeper");
String shopkeeper=shopkeeperNode.getText();
//如果没有店主
if(shopkeeper==""){
System.out.println("还没有店铺");
//设置店主昵称
shopkeeperNode.setText(pgb.getShopkeeper());
//设置店铺名称
Element shopNode=root.element("shop");
shopNode.setText(pgb.getShop());
return true;
}else{
System.out.println(" "+shopkeeper+" "+pgb.getShopkeeper());
//如果是同一个 店铺
if(shopkeeper.equals(pgb.getShopkeeper())){
return true;
}
}
return false;
}
/**
* 修改商品数量
* @param pgb:商品对象
* @param cart:购物车对象
*/
public Document modifyPurchaseNumber(PurchaseGoodsBean pgb,Document cart){
//获得根节点
Element root=cart.getRootElement();
//获得要修改的商品节点
Element goodNode=getNode(pgb.getGoodsId(),cart);
if(goodNode!=null){
//得到商品數量迭代器
Iterator goodsNumberIter=goodNode.elementIterator("goodsNumber");
int goodsNumber=0;
//获得商品数量
if(goodsNumberIter.hasNext()){
Element goodsNumberNode=(Element)goodsNumberIter.next();
goodsNumber=Integer.parseInt(goodsNumberNode.getText());
//修改商品的數量
goodsNumberNode.setText(pgb.getPurchaseNumber()+"");
}
//商品数量的差量
int goodsSub=pgb.getPurchaseNumber()-goodsNumber;
//商品價格迭代器
Iterator goodsPriceIter=goodNode.elementIterator("goodsPrice");
double goodsPrice=0;
//獲得商品價格
if(goodsPriceIter.hasNext()){
Element goodsPriceNode=(Element)goodsPriceIter.next();
goodsPrice=Double.parseDouble(goodsPriceNode.getText());
}
//商品差价
double goodsMoney=goodsPrice*goodsSub;
//获得当前总资金
double totalMoney=Double.parseDouble
(root.element("totalMoney").getText());
//修改总金额
double modifyTotalMoney=goodsMoney+totalMoney;
root.element("totalMoney").setText(modifyTotalMoney+"");
//商品小计迭代器
Iterator goodsSubtotalIter=goodNode.elementIterator("goodsSubtotal");
Element goodsSubtotalNode=(Element)goodsSubtotalIter.next();
//修改小计
double goodsSubtotal=Double.parseDouble(goodsSubtotalNode.getText());
double modifySubtotal=goodsSubtotal+goodsMoney;
goodsSubtotalNode.setText(modifySubtotal+"");
//修改获得积分
Iterator goodsIntegralIter=goodNode.elementIterator("goodsIntegral");
Element goodsIntegralNode=(Element)goodsIntegralIter.next();
int goodsIntegral=(int)modifySubtotal;
goodsIntegralNode.setText(goodsIntegral+"");
}
return cart;
}
/**
* 获得指定ID商品的节点
* @param goodsId:商品ID
* @param cart:购物车对象
* @return:指定ID的商品节点 NULL:没有这个节点
*/
@SuppressWarnings("unchecked")
public Element getNode(String goodsId,Document cart){
//获得商品列表节点
List goodsList= cart.selectNodes("//goodsList/goods");
//迭代器
Iterator goodsIter=goodsList.iterator();
while(goodsIter.hasNext()){
Element goods=(Element)goodsIter.next();
//得到商品ID迭代器
Iterator goodsIdIter=goods.elementIterator("goodsId");
while(goodsIdIter.hasNext()){
Element goodsIdNode=(Element)goodsIdIter.next();
if(goodsIdNode.getText().equals(goodsId))
return goods;
}
}
return null;
}
/**
* 删除指定ID的商品
* @param goodsId:商品ID
* @param cart:购物车对象
*/
public Document deleteGoods(String goodsId,Document cart){
//获得根节点
Element root=cart.getRootElement();
//获得商品列表节点
Element goodsListNode=root.element("goodsList");
//获得要删除的节点
Element goodNode=getNode(goodsId,cart);
if(goodNode==null){
return cart;
}
//获得小计
Iterator goodsSubtotalIter=goodNode.elementIterator("goodsSubtotal");
Element goodsSubtotalNode=(Element)goodsSubtotalIter.next();
double goodsSubtotal=Double.parseDouble(goodsSubtotalNode.getText());
//修改购物车总金额
double totalMoney=Double.parseDouble
(root.element("totalMoney").getText());
double modifyTotalMoney=totalMoney-goodsSubtotal;
root.element("totalMoney").setText(modifyTotalMoney+"");
//删除节点
goodsListNode.remove(goodNode);
System.out.println(cart.asXML());
return cart;
}
/**
* 判断商品是否已经存在
* @param goodsId:商品ID
* @param cart:购物车对象
* @return TRUE:存在 FALSE:不存在
*/
@SuppressWarnings("unchecked")
public boolean isGoodsExist(String goodsId,Document cart){
//获得根节点
Element root=cart.getRootElement();
//获得店主节点
Element shopkeeperNode=root.element("shopkeeper");
String shopkeeper=shopkeeperNode.getText();
//如果没有店主
if(shopkeeper==""){
System.out.println("还没有店铺");
return false;
}
//获得商品列表节点
Element goodsListNode=root.element("goodsList");
//遍历商品列表
java.util.List<Element>goodList=goodsListNode.elements();
for(int i=0;i<goodList.size();i++){
//得到商品节点
Element goodNode=goodList.get(i);
//得到商品ID
Iterator goodsIdIter=goodNode.elementIterator("goodsId");
Element goodsIdNode=(Element)goodsIdIter.next();
String goodsID=goodsIdNode.getText();
//如果存在这样的商品
if(goodsId.equals(goodsID)){
return true;
}
}
return false;
}
}
说明:1.首先你得有dom4j这个解析XML文档的东东,如果感兴趣,到我的附件里面去下载
2.里面有的地方可能要操作数据库,比如根据商品的ID获得商品的图片,名称,价格等等,我这里就手工模拟了!
4.展示购物车商品信息的jsp页面 show_goods.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="org.dom4j.Document"%><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!--引入外部js文件--> <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script> <script src="js/detailInfo.js" type="text/javascript"></script> <style TYPE="text/css"> <!-- A:link{text-decoration:none} A:visited{text-decoration:none} A:hover {color: #ff0000} --> </style> <title>Insert title here</title> </head> <body> <c:out value="商品列表展示" /><br> <x:parse varDom="cartDoc"> ${cart} </x:parse> <c:out value="总金额"/> <x:out select="$cartDoc/cart/totalMoney"/><br> <c:out value="店铺:"/> <x:out select="$cartDoc/cart/shop"/><br> <c:out value="店主昵称:"/> <x:out select="$cartDoc/cart/shopkeeper"/><br> <table border="1"> <tr> <td>商品图片</td> <td>商品名称</td> <td>商品ID</td> <td>商品购买数量</td> <td>商品所属分类</td> <td>商品价格</td> <td>可获得积分</td> <td>小计</td> <td>操作</td> </tr> <x:forEach select="$cartDoc//goods" varStatus="status"> <tr> <td> <img alt="" src="<x:out select="goodsPicture"/>"> </td> <td><x:out select="goodsName"/></td> <td><x:out select="goodsId"/></td> <td align="center"> <a href="" class="subNumber" id="<x:out select="goodsId"/>" name="<x:out select="goodsNumber"/>">-</a> <input id="goodsNumber" size="2" type="text" name="<x:out select="goodsId"/>" value="<x:out select="goodsNumber"/>"> <a href="" class="addNumber" id="<x:out select="goodsId"/>" name="<x:out select="goodsNumber"/>">+</a> </td> <td align="center"><x:out select="goodsCatalog"/></td> <td><x:out select="goodsPrice"/></td> <td><x:out select="goodsIntegral"/></td> <td><x:out select="goodsSubtotal"/></td> <td> <a id="<x:out select="goodsId"/>" href=""οnclick="" name="delete">删除</a> </td> </tr> </x:forEach> </table> </body> </html>
说明:1. 这个页面用到了JSTL(用来展示商品信息)与jquery(用来发送异步请求,比如删除商品,修改商品数量)
想下载JSTL与jquery的 到附件下载
2.看看这段代码:<x:parse varDom="cartDoc"> ${cart} </x:parse> ${cart}:是从session当中取出购物车对象,在<x:parse>当中只能够为xml文件的字符串形式,这就是我为什么把购物车以字符串形式保存在session当中。
3.jquery处理异步请求,请参考下面的js文件
5.jquery AJAX发送异步请求(修改商品数量,删除商品) detailInfo.js
$(document).ready(function() { // 删除商品请求处理 $("a[name='delete']").click( function(){ alert($(this).attr("id")); //AJAX请求 $.ajax({ type:"post", url:"DeleteCartGoodsRequest.do", data:"goodsId="+$(this).attr("id"), success:function(msg){ alert(msg); } }); } ); //商品数量加一处理 $("a[class='addNumber']").click( function(){ //获得商品数量 var goodsNumber=$(this).attr("name")*1+1; //获得商品ID var goodsId=$(this).attr("id"); alert(goodsNumber+"---id---"+goodsId); //AJAX请求 $.ajax({ type:"post", url:"ModifyCartGoodsRequest.do", data:"purchaseNumber="+goodsNumber+"&goodsId="+goodsId, success:function(msg){ alert(msg); } }); } ); //商品数量减一处理 $("a[class='subNumber']").click( function(){ //获得商品数量 var goodsNumber=$(this).attr("name")*1-1; //获得商品ID var goodsId=$(this).attr("id"); alert(goodsNumber+"---id---"+goodsId); //AJAX请求 $.ajax({ type:"post", url:"ModifyCartGoodsRequest.do", data:"purchaseNumber="+goodsNumber+"&goodsId="+goodsId, success:function(msg){ alert(msg); } }); } ); //直接修改商品数量 $("input[id='goodsNumber']").change( function(){ //获得商品数量 var goodsNumber=$(this).attr("value"); //获得商品的ID var goodsId=$(this).attr("name"); alert(goodsNumber+" "+goodsId); //AJAX请求 $.ajax({ type:"post", url:"ModifyCartGoodsRequest.do", data:"purchaseNumber="+goodsNumber+"&goodsId="+goodsId }); } ); });
6.修改商品购买数量java后台处理类: ModifyCartGoodsRequest
package cn.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.dom4j.Document;
import cn.struts.formbean.PurchaseGoodsBean;
/**
* 修改购物车某件商品数量处理类
* @author LI
*
*/
public class ModifyCartGoodsRequest extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//参数类
PurchaseGoodsBean pgb=(PurchaseGoodsBean)form;
//获得修改后的商品数量与商品ID
int purchaseNumber=pgb.getPurchaseNumber();
String goodsId=pgb.getGoodsId();
//调试信息
System.out.println("修改后的商品数量为----->"
+purchaseNumber+"goodsId--->"+goodsId);
//获得session对象
javax.servlet.http.HttpSession session=request.getSession();
//获得购物车对象
String cartString=(String)session.getAttribute("cart");
Document cartXml=null;
if(cartString!=null)
cartXml = org.dom4j.DocumentHelper.parseText(cartString);
//修改商品
Document cart=cn.netjava.utils.XMLCart.getInstance()
.modifyPurchaseNumber(pgb, cartXml);
//购物车放入session中存放
session.setAttribute("cart", cart.asXML());
return mapping.findForward("modifySucc");
}
}
这个就不必多做说明了,下面一个也一样
7.删除商品处理类: CartDeleteGoodsRequest
package cn.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.dom4j.Document;
import cn.struts.formbean.PurchaseGoodsBean;
/**
* 删除购物车里面的商品
* @author LI
*
*/
public class CartDeleteGoodsRequest extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("删除购物车里面的商品");
//参数对象
PurchaseGoodsBean pgb=(PurchaseGoodsBean)form;
//调试信息
System.out.println("goodsId---------->"+pgb.getGoodsId());
//获得购物车对象
HttpSession session=request.getSession();
String cartString =(String)session.getAttribute("cart");
Document cartXml=null;
if(cartString!=null)
cartXml = org.dom4j.DocumentHelper.parseText(cartString);
//删除商品
Document cart=cn.netjava.utils.XMLCart.getInstance()
.deleteGoods(pgb.getGoodsId(), cartXml);
//购物车放入session中存放
session.setAttribute("cart", cart.asXML());
return mapping.findForward("deleteSucc");
}
}
OK,到此一切都弄好了!我基本上是Ctrl+C与Ctrl+V。呵呵...看不懂的地方,欢迎询问!如果认为哪个地方有更好的解决方法。欢迎交流!