购物车的实现

//首先创建一个javabean

package com.ht.qfb;

import java.util.HashMap;

public class Cart

{

private String userID;

private HashMap items;



public Cart()

{

items = new HashMap();

}



//添加商品

public void addItem(String itemID)

{

if(items.containsKey(itemID))

{

int quantity = Integer.parseInt(items.get(itemID).toString());

items.remove(itemID);

items.put(itemID,new Integer(1+quantity));

}

else

items.put(itemID,new Integer(1));

}



//删除商品

public void removeItem(String itemID)

{

items.remove(itemID);

}



//修改商品

public void updateItem(String itemID,int quantity)

{

if(items.containsKey(itemID))

items.remove(itemID);

items.put(itemID,new Integer(quantity));

}



//获得所有商品

public HashMap getItems()

{

return this.items;

}



//设置用户ID

public void setUserID(String id)

{

this.userID = id;

}



//清空购物车

public void clear()

{

items.clear();

}

}

//在JSP页面上显示购物车中的商品

//本JSP页面是通过点击购物按钮时跳到的购物车界面

<%@page contentType="text/html; charset=GBK"%>

<jsp:useBean id="cart" class="com.ht.qfb.Cart" scope="session"/>

<table cellspacing=1 cellpadding=0 width="97%" bgcolor=#cccccc border=0>

<tr bgcolor=#f1f1f1>

<td height="20" align="center"> <strong> 商品编号 </strong> </td>

<td align=middle> <strong>数量</strong> </td>

</tr>

<%

String id=request.getParameter("id");//刚才购买的商品的ID

cart.addItem(id);//添加商品到购物车

java.util.HashMap cart_item=cart.getItems();

Iterator it=cart_item.keySet().iterator();

while(it.hasNext())

{

String itemID=(String)it.next();

%>



<tr bgcolor=#ffffff>

<td height="20" align="center"> <%=itemID%></td>

<td align=middle> <%=cart_item.get(itemID)%> </td>

</tr> <%}%>

</table>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值