新聞中心
用JSP的Session 機(jī)制編寫的程序就可以是你擁有一個功能強(qiáng)大購物車程序,是不是很誘人呢?趕緊開始我們的程序吧

創(chuàng)新新互聯(lián),憑借十年的網(wǎng)站建設(shè)、網(wǎng)站制作經(jīng)驗,本著真心·誠心服務(wù)的企業(yè)理念服務(wù)于成都中小企業(yè)設(shè)計網(wǎng)站有千余家案例。做網(wǎng)站建設(shè),選成都創(chuàng)新互聯(lián)。
JSP Session 機(jī)制購物車之一構(gòu)建的商品類
◆寫一個Goods類,并定義商品的各個屬性,返回商品屬性的方法,以及商品對象進(jìn)行比較的方法
◆Goods.java
- package com.viita.Shop;
- public class Goods implements Comparable {
◆初始化各成員變量
- private String Id = null;//商品的編號Id
- private String name = null;//商品的名稱name
- private float price = 0.00F;//商品的價格price
- private int number = 0;//商品的數(shù)量number
- public Goods(String Id, String name, float price, int number) {
- this.Id = Id;
- this.name = name;
- this.price = price;
- this.number = number;
- }
- public String getId() //返回訂購商品的編號Id
- {
- return this.Id;
- }
- public String getName() //返回訂購商品的名稱name
- {
- return this.name;
- }
- public float getPrice() //返回訂購商品的價格price
- {
- return this.price;
- }
- public int getNumber() //返回訂購商品的數(shù)量number
- {
- return this.number;
- }
- public int compareTo(Object m) {
- // TODO Auto-generated method stub
- Goods n = (Goods) m;
- int comRs = Id.compareTo(n.Id);
- return comRs;
- }
- }
JSP Session 機(jī)制購物車之二購物車實現(xiàn)
◆首先建立Goods(商品)對象goods,并建立建立ArrayList對象ay
◆通過ArrayList對象的方法add()將商品對象添加到ArrayList對象ay中
◆由于ArrayList對象是具有添加和刪除成員的方法,從而實現(xiàn)多個商品存儲管理于ArrayList對象
◆將ArrayList對象ay存儲于session對象當(dāng)中,實現(xiàn)購物車功能
◆shopcar.jsp
- <%@ page language="java" import=" java.sql.*,com.viita.Shop.*,java.util.*" pageEncoding="GBK"%>
- <%
◆設(shè)置編碼格式
- request.setCharacterEncoding("GBK");
◆獲取參數(shù)信息
- String id = request.getParameter("id");
- String name = request.getParameter("name");
- int number = java.lang.Integer.parseInt(request.getParameter("number"));
- float price= java.lang.Float.parseFloat(request.getParameter("price"));
◆建立商品對象和ArrayList對象
- Goods goods = new Goods(id,name,price,number);
- ArrayList ay = null;
◆如果session中從未寫入過,則將建立的商品對象添加到ArrayList對象當(dāng)中,并寫入 session
- if((ArrayList)session.getAttribute("car")==null)
- {
- ay = new ArrayList();
- ay.add(goods);
- session.setAttribute("car",ay);
- response.sendRedirect("order_index.jsp");
- }
◆如果寫如過,則將商品對象添加到ArrayList對象當(dāng)中,并寫入 session
- else
- {
- ay=(ArrayList)session.getAttribute("car");
◆如果ArrayList 對象為空,則直接添加到ArrayList對象當(dāng)中
- if(ay.isEmpty())
- {
- ay.add(goods);
- session.setAttribute("car",ay);
- response.sendRedirect("order_index.jsp");
- }
◆如果ArrayList 對象不為空,則判斷購入商品是否已經(jīng)存在于車中
- else
- {
- Iterator it = ay.iterator();
- for(int i = 0;i
- {
- Goods shop = (Goods)it.next();
◆如果購入商品已經(jīng)存在,則打印輸入提示信息
- if(shop.compareTo(goods)==0)
- {
- out.println("


咨詢
建站咨詢