java使用session实现购物车功能?

首先,我们应该想到,一般购物车具有的功能有哪些,要做好这个购物车,我们至少要实现5个功能,

  1. 向购物车添加商品,(首先,应该判断该商品是否在购物车中已经存在,若存在,该商品数量+1,若不存在,则将该商品加入购物车并数量设置为1)

  2. 修改商品的数量(请求一个servlet,并根据该商品的某个唯一属性修改其数量)

  3. 删除商品(通过请求servlet并根据要删除商品的唯一属性将其删除)

  4. 清空购物车(请求servlet将购物车清空)

  5. 获得商品的初始价格

  6. 获得商品的会员价格

  7. 获得优惠价格

  8. 获得购物车中的所有商品
    当分析到这里,可能很多朋友会立马想到list,没错,用list绝对可以实现这些功能,但是在这里,map更为简单,以清空购物车为例,如果我们使用list,我们清空时必须通过循环来删除,但map有个clear方法,直接就可以将购物车清空!接下来,请看代码(以书为例):
    GwcItem实体类(这里将购物车中要显示的属性封装成GwcItem实体类):

    public class GwcItem {
    private int bookId;
    private String bookName;
    private String smallImg;
    private float price;
    private float hyPrice;
    private int num;

    	public GwcItem() {
    		// TODO Auto-generated constructor stub
    	}
    
    	public GwcItem(int bookId, String bookName, String smallImg, float price,
    			float hyPrice, int num) {
    		super();
    		this.bookId = bookId;
    		this.bookName = bookName;
    		this.smallImg = smallImg;
    		this.price = price;
    		this.hyPrice = hyPrice;
    		this.num = num;
    	}
    
    	public int getBookId() {
    		return bookId;
    	}
    
    	public void setBookId(int bookId) {
    		this.bookId = bookId;
    	}
    
    	public String getBookName() {
    		return bookName;
    	}
    
    	public void setBookName(String bookName) {
    		this.bookName = bookName;
    	}
    
    	public String getSmallImg() {
    		return smallImg;
    	}
    
    	public void setSmallImg(String smallImg) {
    		this.smallImg = smallImg;
    	}
    
    	public float getPrice() {
    		return price;
    	}
    
    	public void setPrice(float price) {
    		this.price = price;
    	}
    
    	public float getHyPrice() {
    		return hyPrice;
    	}
    
    	public void setHyPrice(float hyPrice) {
    		this.hyPrice = hyPrice;
    	}
    
    	public int getNum() {
    		return num;
    	}
    
    	public void setNum(int num) {
    		this.num = num;
    	}
    }
    

购物车接口:

import java.util.Collection;
public interface IGwc {
public void addItem(GwcItem gwcItem);
public void updateItemNum(int bookId, int num);
public void deleteItem(int bookId);
public void clear();
/*
* 得到原始总价
/
public float getOldPrices();
/

* 得到会员价
*/
public float getHyPrices();
public float getYhPrices();
public Collection getAllItems();
}
实现购物车接口:
import java.util.Collection;
import java.util.Hashtable;
import java.util.Set;
public class Gwc implements IGwc{
private Hashtable<Integer, GwcItem> gwcItems = new Hashtable<Integer, GwcItem>();

@Override
public void addItem(GwcItem gwcItem) {
	Set<Integer> keys = gwcItems.keySet();
	//若包含,则购物车中已经存在该商品
	if (keys.contains(gwcItem.getBookId())) {
		GwcItem oldGwcItem = gwcItems.get(gwcItem.getBookId());
		oldGwcItem.setNum(oldGwcItem.getNum()+1);
	} else {
		gwcItems.put(gwcItem.getBookId(), gwcItem);
	}
}

@Override
public void updateItemNum(int bookId, int num) {
	GwcItem gwcItem = gwcItems.get(bookId);
	gwcItem.setNum(num);
	//引用传递
	gwcItems.put(bookId, gwcItem);
}

@Override
public void deleteItem(int bookId) {
	gwcItems.remove(bookId);
}

@Override
public void clear() {
	gwcItems.clear();
}

@Override
public float getOldPrices() {
	float prices = 0;
	Collection<GwcItem> list = gwcItems.values();
	for (GwcItem gwcItem : list) {
		prices += gwcItem.getPrice()*gwcItem.getNum();
	}
	return prices;
}

@Override
public float getHyPrices() {
	float prices = 0;
	Collection<GwcItem> list = gwcItems.values();
	for (GwcItem gwcItem : list) {
		prices = prices + gwcItem.getHyPrice() * gwcItem.getNum();
	}
	return prices;
}

@Override
public Collection<GwcItem> getAllItems() {
	return gwcItems.values();
}

@Override
public float getYhPrices() {
	return this.getOldPrices() - this.getHyPrices();
}

}

添加商品的servlet:

 import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import com.jinzhi.DAO.IBookInfoDAO;
    import com.jinzhi.DAO.impl.BookInfoDAOImpl;
    import com.jinzhi.entity.BookInfo;
    
    public class GwcItemAddServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		int bookId = Integer.parseInt(request.getParameter("bookId"));
    		IBookInfoDAO bookInfoDAO = new BookInfoDAOImpl();
    		BookInfo bookInfo = bookInfoDAO.findById(bookId);
    		GwcItem gwcItem = new GwcItem(bookId, bookInfo.getBookName(), bookInfo.getSmallImg(), bookInfo.getPrice(), bookInfo.getHyPrice(), 1);
    		
    		HttpSession session = request.getSession();
    		Gwc gwc = (Gwc) session.getAttribute("gwc");
    		if (gwc == null) {
    			gwc = new Gwc();
    		}
    		gwc.addItem(gwcItem);
    		session.setAttribute("gwc", gwc);
    		response.sendRedirect("gwc.jsp");
    	}
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    	}
    }

清空购物车:

  import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    public class GwcItemClearServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		HttpSession session = request.getSession();
    		Gwc gwc = (Gwc) session.getAttribute("gwc");
    		gwc.clear();
    		response.sendRedirect("gwc.jsp");
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    	}
    }

删除商品servlet:

 import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    public class GwcItemDeleteServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		HttpSession session = request.getSession();
    		Gwc gwc = (Gwc) session.getAttribute("gwc");
    		int bookId = Integer.parseInt(request.getParameter("bookId"));
    		gwc.deleteItem(bookId);
    		response.sendRedirect("gwc.jsp");
    	}
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    	}
    }

修改商品数量的servlet:

   import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    public class GwcItemDeleteServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		HttpSession session = request.getSession();
    		Gwc gwc = (Gwc) session.getAttribute("gwc");
    		int bookId = Integer.parseInt(request.getParameter("bookId"));
    		gwc.deleteItem(bookId);
    		response.sendRedirect("gwc.jsp");
    	}
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    	}
    }

jsp页面代码:

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta name="viewport" content="width=1024" />
<title>我的购物袋</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<link rel="stylesheet" href="style/public.css" type="text/css" />
<script type="text/javascript">
	function updateGwcItem(bookId,num){
		if(isNaN(num)){
			alert("请输入数字");
			return;
		}
		if(num < 1){
			alert("书的数量不能小于1哦!");
			return;
		}
		if (num%1 != 0) {
			alert("书的数量不能为小数哦!");
			return;
		}
	location.href="${pageContext.request.contextPath}/GwcItemUpdateServlet?bookId="+bookId+"&num="+num;
	}
</script>
</head>
<body>
	<table width="100%" border="0" cellspacing="" cellpadding="5">
		  <tr>
			<th>商品名称</th>
			<th>单价(元)</th>
			<th>数量</th>
			<th>优惠</th>
			<th>小计(元)</th>
			<th>赠送积分</th>
			<th>操作</th>
		  </tr>
		  <c:forEach items="${gwc.getAllItems()}" var="gwcItem">
		  		<tr>
			<td align="left" width="400"><div class="shpic">
			<img src="${pageContext.request.contextPath}/images/imgsx/${gwcItem.smallImg}" /></div>
			<span class="shname"><a href="${pageContext.request.contextPath}/BookInfoDetailServlet?id=${gwcItem.bookId}">${gwcItem.bookName}</a><br />
		   <span class="fccc"> 颜色:极乐绿 尺码:170/</span>92A</span></td>
			<td align="center" width="100">售 价 :${gwcItem.hyPrice}<span class="fccc"><del> <br />
		    市场价:
          ${gwcItem.price} </del></span></td>
			<td align="center" width="70"><a onclick="updateGwcItem(${gwcItem.bookId},${gwcItem.num-1})" title="减-" style="cursor:pointer" class="btn_minus_s">-</a> 
			 <input name="num" type="text" class="text_num"id="num_2073165120748" onchange="updateGwcItem(${gwcItem.bookId},this.value)" value="${gwcItem.num}" size="2" maxlength="2" autocomplete="off" now_data2073165120748="1"/>
			<a onclick="updateGwcItem(${gwcItem.bookId},${gwcItem.num+1})" title="加+" style="cursor:pointer" class="btn_plus_s">+</a></td>
			<td align="center" width="50">${(gwcItem.price - gwcItem.hyPrice)*gwcItem.num}</td>
			<td align="center" width="60">${gwcItem.hyPrice*gwcItem.num}</td>
			<td align="center" width="50"><span class="cols col-6"><span>0 </span></span></td>
			<td align="center" width="100"><span class="cols col-7"><a href="${pageContext.request.contextPath}/FavoriteServlet?bookId=${gwcItem.bookId}" style="cursor:pointer">加入收藏</a> | <a href="${pageContext.request.contextPath}/GwcItemDeleteServlet?bookId=${gwcItem.bookId}" onclick="return confirm('您确定要删除${gwcItem.bookName}吗?')" style="cursor:pointer">删除</a></span></td>
		  </tr>
		  <tr><td colspan="7" align="right" class="zongj">总价:${gwc.getOldPrices()}元 -
                        优惠:${gwc.getYhPrices()}元
                        <input type="hidden" name="packagehidden" id="packagehidden" value=""> 
                      = 商品总计(不含运费):<span class="fred">¥${gwc.getHyPrices()}</span>  获得:0 积分点</td>
		  </tr>
		  </c:forEach>
		  <tr><td colspan="7"><div class="left">
					 <a class="btn_clear_cart" href="${pageContext.request.contextPath}/InitIndexServlet"><img src="images/jxgw.png"></a>
                    <a  class="btn_clear_cart" href="${pageContext.request.contextPath}/GwcItemClearServlet"><img src="images/qkgw.png"></a>
                    </div>
					 <div class="right" >
					<a href="${pageContext.request.contextPath}/InitOrderServlet" class="bg_cart btn_check_order" >
					<img src="images/jies.png"></a>
					</div>
         </td></tr>
		</table>
</body>
页面显示结果(部分代码未展示):

在这里插入图片描述

笔者刚开始运营公众号啦,感兴趣的可关注我的公众号,欢迎交流!

image.png

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值