iT邦幫忙

DAY 27
4

JSP 學習分享系列 第 27

JSP 購物車的範例

JSP 購物車的範例
1.建立一個DummyCart的物件來儲存所選的項目
2.把已經選擇的物品列到最上面,並include一個下拉式選單
3.把可以選擇的物品用下拉式選單列出
建立一個DummyCart的物件來儲存所選的項目
=== DummyCart.java ===

package sessions;

import java.util.Vector;

public class DummyCart {
    Vector<String> v = new Vector<String>();
    String submit = null;
    String item = null;
    
    private void addItem(String name) {
        v.addElement(name);
    }

    private void removeItem(String name) {
        v.removeElement(name);
    }

    public void setItem(String name) {
        item = name;
    }
    
    public void setSubmit(String s) {
        submit = s;
    }

    public String[] getItems() {
        String[] s = new String[v.size()];
        v.copyInto(s);
        return s;
    }
    
    public void processRequest() {
        // null value for submit - user hit enter instead of clicking on 
        // "add" or "remove"
        if (submit == null || submit.equals("add"))
            addItem(item);
        else if (submit.equals("remove")) 
            removeItem(item);
        
        // reset at the end of the request
        reset();
    }

    // reset
    private void reset() {
        submit = null;
        item = null;
    }
}

把已經選擇的物品列到最上面,並include一個下拉式選單
=== cart.jsp ===

<jsp:useBean id="cart" scope="session" class="sessions.DummyCart" />

<jsp:setProperty name="cart" property="*" />
<%
	cart.processRequest();
%>

<FONT size = 5 COLOR="#CC0000">
<br> You have the following items in your cart:
<ol>
<% 
	String[] items = cart.getItems();
	for (int i=0; i<items.length; i++) {
%>
<li> <% out.print(util.HTMLFilter.filter(items[i])); %> 
<%
	}
%>
</ol>

</FONT>

<hr>
<%@ include file ="carts.html" %>

把可以選擇的物品用下拉式選單列出
=== carts.html ===

    <title>carts</title>


 <body bgcolor="white">
<font size = 5 color="#CC0000">

<form type=POST action=carts.jsp>
<BR>
Please enter item to add or remove:
<br>
Add Item:
<SELECT NAME="item">
<OPTION>Beavis & Butt-head Video collection
<OPTION>X-files movie
<OPTION>Twin peaks tapes
<OPTION>NIN CD
<OPTION>JSP Book
<OPTION>Concert tickets
<OPTION>Love life
<OPTION>Switch blade
<OPTION>Rex, Rugs & Rock n' Roll
</SELECT>
<br> <br>
<INPUT TYPE=submit name="submit" value="add">
<INPUT TYPE=submit name="submit" value="remove">
</form>
</FONT>

上一篇
JSP 應用 抓取網頁內容
下一篇
JSP 猜數字範例
系列文
JSP 學習分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
海綿寶寶
iT邦大神 1 級 ‧ 2009-11-08 15:55:06

建議要加一些自己的意見或說明
看的人會比較看得懂

是,老大

我要留言

立即登入留言