天天看點

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);

}

}

}