jsp和JAVA购物车_JSP实现的简单购物车详解

goods_form.html

欢迎光临购物车

h1 {

color: #F66;

}

欢迎光临购物车

请选择您要购买的商品: 

电脑

MP3

MP4

MP5

洗衣机

电视机

购买数量: 

goods_do.jsp

欢迎光临购物车

td {

color: #333;

font-family: "微软雅黑", Verdana, sans-serif, "宋体";

width: 150px;

border-bottom-width: 1px;

border-bottom-style: dashed;

border-bottom-color: #999;

}

table {

width: 400px;

text-align: center;

margin-right: auto;

margin-left: auto;

border: 2px solid #666;

}

h1 {

color: #F66;

}

//设置编码格式

request.setCharacterEncoding("utf-8");

//获取所要添加到购物车的商品名称和数量

String sGoodsName = request.getParameter("GoodsName");

String sGoodsNumber = request.getParameter("GoodsNumber");

//根据商品名称是否为空判断是否需要保存商品信息

if (sGoodsName != null && sGoodsName != "") {

int iGoodsNumber = Integer.parseInt(sGoodsNumber);

Goods.add(sGoodsName, iGoodsNumber);

}

//获取购物车对象信息

Hashtable h = Goods.show();

//获取购物车中所有商品名称

Enumeration e = h.keys();

//keys(),返回此哈希表中的键的枚举。

%>

欢迎光临购物车

您的购物信息如下:

while (e.hasMoreElements()) {

//根据商品名称获得相应商品数量

String sTemp = e.nextElement().toString();

int iTemp = ((Integer) h.get(sTemp)).intValue();

%>

:

}

%>

onClick="javascript:window.location='goods_form.html'">

goods_delete.jsp

欢迎光临购物车

欢迎光临购物车

request.setCharacterEncoding("utf-8");

//获取所要删除的商品名称

String sGoodsName = request.getParameter("deleteName");

//删除对应的商品信息

Goods.delete(sGoodsName);

//跳转当前页面

response.sendRedirect("goods_do.jsp");

%>

Goods.java

package com.demo;

import java.util.*;

import java.io.*;

/**

* 购物车

*

*/

public class Goods implements Serializable {

public Hashtable Goods = new Hashtable();

// 构造函数

public void Goods() {

}

// 将某个商品信息加入购物车

public void add(String GoodsName, int GoodsNumber) {

if (Goods.containsKey(GoodsName))

// containsKey,测试指定对象是否为此哈希表中的键。

{// 购物车中存在此商品

int iTemp = ((Integer) Goods.get(GoodsName)).intValue();

// intValue(),以 int 类型返回该 Integer 的值。

iTemp = iTemp + GoodsNumber;

Goods.put(GoodsName, new Integer(iTemp));

} else {// 购物车中不存在此商品

Goods.put(GoodsName, new Integer(GoodsNumber));

}

}

// 获取购物车中所有商品

public Hashtable show() {

return Goods;

}

// 从购物车中删除一件商品

public void delete(String GoodsName) {

int num = Integer.parseInt(Goods.get(GoodsName).toString()) - 1;

if (num == 0) {

Goods.remove(GoodsName);

} else {

Goods.put(GoodsName, num);

}

}

}


版权声明:本文为weixin_42097668原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。