點擊數(shù)量進(jìn)入購物車頁面,這個應(yīng)該好做吧,跳動一個Action轉(zhuǎn)發(fā)到購物車頁面
創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供疏附網(wǎng)站建設(shè)、疏附做網(wǎng)站、疏附網(wǎng)站設(shè)計、疏附網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、疏附企業(yè)網(wǎng)站模板建站服務(wù),十載疏附做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
下面是我的圖書購物車(自己寫的)
package com.jc.ts.services;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.jc.ts.entity.BookCar;
import com.jc.ts.entity.BookInfo;
/**
* 該類提供購物車的操作
* */
public class CartItemsService {
private MapString,BookCar itemMap=null;//購物車Map集合
private CollectionBookCar items;//購物車項
public CartItemsService()
{
itemMap=new HashMapString ,BookCar();
}
public CollectionBookCar getItems() {
return items;
}
public void setItems(CollectionBookCar items) {
this.items = items;
}
public MapString, BookCar getItemMap() {
return itemMap;
}
public void setItemMap(MapString, BookCar itemMap) {
this.itemMap = itemMap;
}
public int getBookCarSize()
{
return itemMap.size();
}
public boolean containById(String bookid)
{
return itemMap.containsKey(bookid);
}
public void addBookCarItems(BookInfo bookInfo)
{
if(bookInfo!=null)
{
BookCar bookCar=(BookCar)itemMap.get(bookInfo.getBid());
if(bookCar==null)
{
bookCar=new BookCar();
bookCar.setBookinfo(bookInfo);
bookCar.increaseQuantity();
itemMap.put(bookInfo.getBid(),bookCar);
items=itemMap.values();
}else {
bookCar.increaseQuantity();
}
}
}
public BookInfo removeCarItem(String bookid)
{
BookCar bookCar=itemMap.remove(bookid);
if(bookCar==null)
{
return null;
}
items=itemMap.values();
return bookCar.getBookinfo();
}
public BigDecimal getBookCarTotal()//獲得總金額
{
BigDecimal carTotal=new BigDecimal("0.00");
IteratorBookCar iterator=this.getAllCartItems();
while(iterator.hasNext())
{
BookCar bookCar=iterator.next();
BigDecimal carPrice=bookCar.getBookinfo().getBprice();
BigDecimal quantity=new BigDecimal(String.valueOf(bookCar.getQuantity()));
carTotal=carTotal.add(carPrice.multiply(quantity));
}
return carTotal;
}
public IteratorBookCar getAllCartItems(){
return itemMap.values().iterator();
}
public void increaseQuantityById(String bookid)
{
BookCar bookCar=itemMap.get(bookid);
if(bookCar!=null)
{
bookCar.increaseQuantity();
}
}
public void setQuantityById(String bookid,int quantity)//根據(jù)圖書ID增加數(shù)量
{
BookCar bookCar=itemMap.get(bookid);
if(bookCar!=null)
{
bookCar.setQuantity(quantity);
}
}
public void clear(){
itemMap.clear();
}
}
修改后傳入這個方法就可以了setQuantityById()
★★★ 注意購物車一定要用Map 不能用List或ArrayList
因為購物車是顧客頻繁操作的功能
Map在取值或刪除值的效率比List或ArrayList要高的多
它基本不需要時間,而List或ArrayList還要遍歷。。。。。。
希望對你有幫助!!
以前學(xué)習(xí)java又做個實例,挺值得學(xué)習(xí)的。1.首先我先列出我們所需要的java類結(jié)構(gòu)。1)Database.java---------模擬存儲商品的數(shù)據(jù)庫。2)McBean.java------------商品實體類,一個普通的javabean,里面有商品的基本屬性。3)OrderItemBean.java---訂單表。4)ShoppingCar.java------這個就是最主要的購物車,當(dāng)然比較簡單。5)TestShoppingCar.java---這個是測試類。2.下面貼出具體代碼并帶關(guān)鍵注釋。---Database.javapublicclassDatabase{/*采用Map存儲商品數(shù)據(jù),為什么呢?我覺得這個問題你自己需要想下。*Integer為Map的key值,McBean為Map的value值。*/privatestaticMapdata=newHashMap();publicDatabase(){McBeanbean=newMcBean();bean.setId(1);bean.setName("地瓜");bean.setPrice(2.0);bean.setInstuction("新鮮的地瓜");data.put(1,bean);//把商品放入Mapbean=newMcBean();bean.setId(2);bean.setName("土豆");bean.setPrice(1.2);bean.setInstuction("又好又大的土豆");data.put(2,bean);//把商品放入Mapbean=newMcBean();bean.setId(3);bean.setName("絲瓜");bean.setPrice(1.5);bean.setInstuction("本地絲瓜");data.put(3,bean);//把商品放入Map}publicvoidsetMcBean(McBeanmcBean){data.put(mcBean.getId(),mcBean);}publicMcBeangetMcBean(intnid){returndata.get(nid);}}---McBean.javapublicclassMcBean{privateintid;//商品編號privateStringname;//商品名privatedoubleprice;//商品價格privateStringinstuction;//商品說明publicintgetId(){returnid;}publicvoidsetId(intid){this.id=id;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicdoublegetPrice(){returnprice;}publicvoidsetPrice(doubleprice){this.price=price;}publicStringgetInstuction(){returninstuction;}publicvoidsetInstuction(Stringinstuction){this.instuction=instuction;}}---ShoppingCar.javapublicclassShoppingCar{privatedoubletotalPrice;//購物車所有商品總價格privateinttotalCount;//購物車所有商品數(shù)量privateMapitemMap;//商品編號與訂單項的鍵值對publicShoppingCar(){itemMap=newHashMap();}publicvoidbuy(intnid){OrderItemBeanorder=itemMap.get(nid);McBeanmb;if(order==null){mb=newDatabase().getMcBean(nid);order=newOrderItemBean(mb,1);itemMap.put(nid,order);update(nid,1);}else{order.setCount(order.getCount()+1);update(nid,1);}}publicvoiddelete(intnid){OrderItemBeandelorder=itemMap.remove(nid);totalCount=totalCount-delorder.getCount();totalPrice=totalPrice-delorder.getThing().getPrice()*delorder.getCount();}publicvoidupdate(intnid,intcount){OrderItemBeanupdorder=itemMap.get(nid);totalCount=totalCount+count;totalPrice=totalPrice+updorder.getThing().getPrice()*count;}publicvoidclear(){itemMap.clear();totalCount=0;totalPrice=0.0;}publicvoidshow(){DecimalFormatdf=newDecimalFormat("¤#.##");System.out.println("商品編號\t商品名稱\t單價\t購買數(shù)量\t總價");Setset=itemMap.keySet();Iteratorit=set.iterator();while(it.hasNext()){OrderItemBeanorder=itemMap.get(it.next());System.out.println(order.getThing().getId()+"\t"+order.getThing().getName()+"\t"+df.format(order.getThing().getPrice())+"\t"+order.getCount()+"\t"+df.format(order.getCount()*order.getThing().getPrice()));}System.out.println("合計:總數(shù)量:"+df.format(totalCount)+"總價格:"+df.format(totalPrice));System.out.println("**********************************************");}}---OrderItemBean.javapublicclassOrderItemBean{privateMcBeanthing;//商品的實體privateintcount;//商品的數(shù)量publicOrderItemBean(McBeanthing,intcount){super();this.thing=thing;this.count=count;}publicMcBeangetThing(){returnthing;}publicvoidsetThing(McBeanthing){this.thing=thing;}publicintgetCount(){returncount;}publicvoidsetCount(intcount){this.count=count;}}---TestShoppingCar.javapackagecom.shop;publicclassTestShoppingCar{publicstaticvoidmain(String[]args){ShoppingCars=newShoppingCar();s.buy(1);//購買商品編號1的商品s.buy(1);s.buy(2);s.buy(3);s.buy(1);s.show();//顯示購物車的信息s.delete(1);//刪除商品編號為1的商品s.show();s.clear();s.show();}}3.打印輸出結(jié)果商品編號商品名稱單價購買數(shù)量總價1地瓜¥23¥62土豆¥1.21¥1.23絲瓜¥1.51¥1.5合計:總數(shù)量:¥5總價格:¥8.7**********************************************商品編號商品名稱單價購買數(shù)量總價2土豆¥1.21¥1.23絲瓜¥1.51¥1.5合計:總數(shù)量:¥2總價格:¥2.7**********************************************商品編號商品名稱單價購買數(shù)量總價合計:總數(shù)量:¥0總價格:¥0**********************************************4.打字太累了,比較匆忙,但是主要靠你自己領(lǐng)會。哪里不清楚再提出來。
package?Test;
import?java.util.LinkedHashMap;
import?java.util.Map;
import?java.util.Map.Entry;
import?java.util.Scanner;
public?class?Test?{
public?static?void?main(String[]?args)?{
init();//初始化
MapString,String?map?=?new?LinkedHashMap();
while(true){
Scanner?in=?new?Scanner(System.in);
map?=?buy(in,map);//選擇
System.out.println();
System.out.println("還要繼續(xù)購物嗎?(Y/N)");
String?jx?=?in.nextLine();
if(jx.equals("N")){
break;
}
}
print(map);
}
public?static?void?print(MapString,?String?m){
System.out.println("\n\n\n******************");
System.out.println("???????購物車清單");
Integer?hj?=?0;
for?(EntryString,?String?entry?:?m.entrySet())?{
String?key?=?entry.getKey();
String?value?=?entry.getValue();
if(key.equals("1")){
hj?+=?Integer.parseInt(value)*3;
System.out.println("哇哈哈純凈水:?"+value+"件,合計:¥"+Integer.parseInt(value)*3);
}else?if(key.equals("2")){
hj?+=?Integer.parseInt(value)*5;
System.out.println("康師傅方便面:?"+value+"件,合計:¥"+Integer.parseInt(value)*5);
}else?if(key.equals("3")){
hj?+=?Integer.parseInt(value)*4;
System.out.println("可口可樂:?"+value+"件,合計:¥"+Integer.parseInt(value)*4);
}
}
System.out.println("合計金額:¥"+hj);
}
public?static?void?init(){
System.out.println("******************");
System.out.println("\t商品列表\n");
System.out.println("??????????????商品名稱????????????????價格");
System.out.println("1.???哇哈哈純凈水????????¥3");
System.out.println("2.???康師傅方便面????????¥5");
System.out.println("3.???可口可樂????????????????¥4");
System.out.println("******************");
}
public?static?MapString,String?buy(Scanner?scan,MapString,String?m){
System.out.print("請輸入編號:");
String?bh?=?scan.nextLine();
System.out.print("請輸入購買數(shù)量:");
String?num?=?scan.nextLine();
if(m.size()0??m.keySet().contains(bh)){
m.put(bh,(Integer.parseInt(bh)+Integer.parseInt(num))+"");
}else{
m.put(bh,?num);
}
return?m;
}
}
import java.awt.*;
import java.awt.event.*;
class ShopFrame extends Frame implements ActionListener
{ Label label1,label2,label3,label4;
Button button1,button2,button3,button4,button5;
TextArea text;
Panel panel1,panel2;
static float sum=0.0f;
ShopFrame(String s)
{ super(s);
setLayout(new BorderLayout());
label1=new Label("面紙:3元",Label.LEFT);
label2=new Label("鋼筆:5元",Label.LEFT);
label3=new Label("書:10元",Label.LEFT);
label4=new Label("襪子:8元",Label.LEFT);
button1=new Button("加入購物車");
button2=new Button("加入購物車");
button3=new Button("加入購物車");
button4=new Button("加入購物車");
button5=new Button("查看購物車");
text=new TextArea("商品有:"+"\n",5,10);
text.setEditable(false);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
panel1=new Panel();
panel2=new Panel();
panel1.add(label1);
panel1.add(button1);
panel1.add(label2);
panel1.add(button2);
panel1.add(label3);
panel1.add(button3);
panel1.add(label4);
panel1.add(button4);
panel2.setLayout(new BorderLayout());
panel2.add(button5,BorderLayout.NORTH);
panel2.add(text,BorderLayout.SOUTH);
this.add(panel1,BorderLayout.CENTER);
this.add(panel2,BorderLayout.SOUTH);
setBounds(100,100,350,250);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==button1)
{ text.append("一個面紙、");
sum=sum+3;
}
else if(e.getSource()==button2)
{ text.append("一只鋼筆、");
sum=sum+5;
}
else if(e.getSource()==button3)
{ text.append("一本書、");
sum=sum+10;
}
else if(e.getSource()==button4)
{ text.append("一雙襪子、");
sum=sum+8;
}
else if(e.getSource()==button5)
{
text.append("\n"+"總價為:"+"\n"+sum);
}
}
}
public class Shopping {
public static void main(String[] args) {
new ShopFrame("購物車");
}
}
我沒用Swing可能顯示不出來你的效果。不滿意得話我在給你編一個。
頁面jsp :
%@?page?language="java"?contentType="text/html;?charset=utf-8"
pageEncoding="utf-8"%
%@?taglib?prefix="c"?uri="
%@?taglib?uri="
!DOCTYPE?html?PUBLIC?"-//W3C//DTD?XHTML?1.0?Transitional//EN"?"
html?xmlns="
head
meta?http-equiv="Content-Type"?content="text/html;?charset=utf-8"?/
title易買網(wǎng)?-?首頁/title
link?type="text/css"?rel="stylesheet"?href="${pageContext.request.contextPath?}/css/style.css"?/
script?type="text/javascript"?src="${pageContext.request.contextPath?}/js/jquery-2.1.1.js"/script
script?type="text/javascript"
var?contextPath?=?'${pageContext.request.contextPath?}';
/script
script?type="text/javascript"?src="${pageContext.request.contextPath?}/js/shopping.js"/script
/head
body
jsp:include?page="top.jsp"?/
div?id="position"?class="wrap"
您現(xiàn)在的位置:a?href="Home"易買網(wǎng)/a?gt;?購物車
/div
div?class="wrap"
div?id="shopping"
form?action=""?method="post"
table
tr
th商品名稱/th
th商品價格/th
th購買數(shù)量/th
th操作/th
/tr
c:forEach?items="${sessionScope.shopCar}"??var="item"?varStatus="status"
tr?id="product_id_${item.proId}"
td?class="thumb"img?src="${item.proImg?}"?height="50"?width="30"?/a?href="Product?action=viewentityId=${item.proId}"${item.proName}/a/td
td?class="price"?id="price_id_1"
spanfmt:formatNumber?value="${item.proPrice}"?type="NUMBER"?minFractionDigits="2"?//span
input?type="hidden"?value="${item.proPrice}"?/
/td
td?class="number"
dl
dtspan?onclick="sub('number_id_${item.proId}','${item.proId}')"-/spaninput?id="number_id_${item.proId}"?type="text"?readonly="readonly"?name="number"?value="${item.proNum}"?/span?onclick="addNum('number_id_${item.proId}','${item.proId}')"+/span/dt
/dl
/td
td?class="delete"a?href="javascript:deleteItem('product_id_${item.proId}','${item.proId}')"刪除/a/td
/tr
/c:forEach
/table
div?class="button"input?type="submit"?value=""?//div
/form
/div
/div
div?id="footer"
Copyright?copy;??kaka??292817678?itjob??遠(yuǎn)標(biāo)培訓(xùn).?
/div
/body
/html
頁面關(guān)聯(lián)的js 自己去網(wǎng)上下載一個jquery
/*數(shù)量減少*/
function?sub(id,proId){
//購買數(shù)量的值
var?num?=?$('#'+id).val();
if(num??1){
$('#'+id).val(num?-?1);
}
edit(id,proId);
}
function?edit(id,proId){
var?url?=?contextPath?+?'/HomeCarManager';
//修改后的數(shù)量,購物明細(xì)的商品的id
num?=?$('#'+id).val();
$.post(url,{"num":num,"proId":proId},function?(msg){
/*
if(msg?==?'true'){
alert('修改成功');
}?else?{
alert('修改失敗');
}*/
});
}
/**
*?數(shù)量增加
*?@param?{}?id
*/
function?addNum(id,proId){
//購買數(shù)量的值
var?num?=?$('#'+id).val();
$('#'+id).val(parseInt(num)?+?1);
edit(id,proId);
}
/**
*?刪除購物明細(xì)
*/
function?deleteItem(trId,proId){
//
//console.log($("#"+trId));
//js刪除頁面節(jié)點
//$("#"+trId).remove();
var?url?=?contextPath?+?'/HomeCarManager';
$.post(url,{"proId":proId},function?(msg){
if(msg?==?'true'){
//js刪除頁面節(jié)點
$("#"+trId).remove();
}
});
}
后臺servlet1
package?com.kaka.web;
import?java.io.IOException;
import?java.io.PrintWriter;
import?java.util.ArrayList;
import?java.util.List;
import?javax.servlet.ServletException;
import?javax.servlet.http.HttpServlet;
import?javax.servlet.http.HttpServletRequest;
import?javax.servlet.http.HttpServletResponse;
/**
*?購物車處理類
*?@author?@author?ITJob?遠(yuǎn)標(biāo)培訓(xùn)
*
*/
import?com.kaka.entity.Items;
import?com.kaka.entity.Product;
import?com.kaka.service.ProductService;
import?com.kaka.service.impl.ProductServiceImpl;
public?class?HomeCar?extends?HttpServlet?{
private?static?final?long?serialVersionUID?=?1L;
ProductService?ps?=?new?ProductServiceImpl();
@Override
protected?void?doPost(HttpServletRequest?req,?HttpServletResponse?resp)?throws?ServletException,?IOException?{
//獲取商品的id
String?proId?=?req.getParameter("proId");
resp.setContentType("text/html;charset=UTF-8");
PrintWriter?writer?=?resp.getWriter();
if(null?!=?proId??!"".equals(proId)){
//返回添加購物車成功
//System.out.println("============="?+?proId);
//根據(jù)商品的id查詢商品
try?{
Integer?pId?=?Integer.parseInt(proId);
Product?product?=?ps.findProductById(pId);
if(null?!=?product){
//查詢到了商品,將商品的相關(guān)參數(shù)構(gòu)建一個購物明細(xì)放入到購物車
Items?it?=?new?Items();
it.setProId(product.getProId());
it.setProName(product.getProName());
it.setProPrice(product.getProPrice());
it.setProImg(product.getProImg());
//先判斷session范圍是否有購物車
ListItems?shopCar?=?(ListItems)req.getSession().getAttribute("shopCar");
if(null?==?shopCar){
//購物車
shopCar?=?new?ArrayListItems();
}
//將商品加入到購物車之前,判斷購物車中是否已經(jīng)包含了該購物明細(xì),如果包含了,只需要修改購買的數(shù)量
if(shopCar.contains(it)){
int?index??=?shopCar.indexOf(it);//尋找購物車中包含購物明細(xì)在購物車中位置
Items?items?=?shopCar.get(index);//獲取購物車中存在的購物明細(xì)
items.setProNum(items.getProNum()+1);
}?else?{
shopCar.add(it);
}
//將購物車放入到session訪問
req.getSession().setAttribute("shopCar",?shopCar);
//返回
writer.print(true);
}?else?{
writer.print(false);
}
}?catch?(Exception?e)?{
e.printStackTrace();
writer.print(false);
}
}?else?{
writer.print(false);
}
writer.flush();
writer.close();
}
@Override
protected?void?doGet(HttpServletRequest?req,?HttpServletResponse?resp)?throws?ServletException,?IOException?{
doPost(req,?resp);
}
}
后臺管理servlet?
package?com.kaka.web;
import?java.io.IOException;
import?java.io.PrintWriter;
import?java.util.ArrayList;
import?java.util.List;
import?javax.mail.FetchProfile.Item;
import?javax.servlet.ServletException;
import?javax.servlet.http.HttpServlet;
import?javax.servlet.http.HttpServletRequest;
import?javax.servlet.http.HttpServletResponse;
/**
*?購物車修改
*?@author?ITJob?遠(yuǎn)標(biāo)培訓(xùn)
*
*/
import?com.kaka.entity.Items;
import?com.kaka.entity.Product;
import?com.kaka.service.ProductService;
import?com.kaka.service.impl.ProductServiceImpl;
public?class?HomeCarManager?extends?HttpServlet?{
private?static?final?long?serialVersionUID?=?1L;
ProductService?ps?=?new?ProductServiceImpl();
@Override
protected?void?doPost(HttpServletRequest?req,?HttpServletResponse?resp)?throws?ServletException,?IOException?{
resp.setContentType("text/html;charset=UTF-8");
PrintWriter?writer?=?resp.getWriter();
//獲取參數(shù)
String?proId?=?req.getParameter("proId");
String?num?=?req.getParameter("num");
if(null?!=?proId??null?!=?num
?!"".equals(proId)??!"".equals(num)){
try?{
Integer?pId?=?Integer.parseInt(proId);
Float?pNum?=?Float.parseFloat(num);
//根據(jù)商品的id獲取對應(yīng)的明細(xì)項
//?先判斷session范圍是否有購物車
ListItems?shopCar?=?(ListItems)?req.getSession().getAttribute("shopCar");
for(Items?it?:?shopCar){
if(it.getProId()==?pId){
it.setProNum(pNum);
}
}
writer.print(true);
}?catch?(Exception?e)?{
e.printStackTrace();
}
}?else?{
//刪除的操作
try?{
Integer?pId?=?Integer.parseInt(proId);
//根據(jù)商品的id獲取對應(yīng)的明細(xì)項
//?先判斷session范圍是否有購物車
ListItems?shopCar?=?(ListItems)?req.getSession().getAttribute("shopCar");
Items?items?=?null;
for(Items?it?:?shopCar){
if(it.getProId()==?pId){
items?=?it;
break;
}
}
if(null?!=?items){
shopCar.remove(items);
req.getSession().setAttribute("shopCar",shopCar);
}
writer.print(true);
}?catch?(Exception?e)?{
e.printStackTrace();
}
}
writer.flush();
writer.close();
}
@Override
protected?void?doGet(HttpServletRequest?req,?HttpServletResponse?resp)?throws?ServletException,?IOException?{
doPost(req,?resp);
}
}
用Vector 或者是HashMap去裝
下面有部分代碼你去看吧
package?com.aptech.restrant.DAO;
import?java.util.ArrayList;
import?java.util.HashMap;
import?java.util.List;
import?java.util.Map;
import?java.util.Set;
import?java.sql.Connection;
import?com.aptech.restrant.bean.CartItemBean;
import?com.aptech.restrant.bean.FoodBean;
public?class?CartModel?{
private?Connection?conn;
public?CartModel(Connection?conn)?{
this.conn=conn;
}
/**
*?得到訂餐列表
*?
*?@return
*/
public?List?changeToList(Map?carts)?{
//?將Set中元素轉(zhuǎn)換成數(shù)組,以便使用循環(huán)進(jìn)行遍歷
Object[]?foodItems?=?carts.keySet().toArray();
//?定義double變量total,用于存放購物車內(nèi)餐品總價格
double?total?=?0;
List?list?=?new?ArrayList();
//?循環(huán)遍歷購物車內(nèi)餐品,并顯示各個餐品的餐品名稱,價格,數(shù)量
for?(int?i?=?0;?i??foodItems.length;?i++)?{
//?從Map對象cart中取出第i個餐品,放入cartItem中
CartItemBean?cartItem?=?(CartItemBean)?carts
.get((String)?foodItems[i]);
//?從cartItem中取出FoodBean對象
FoodBean?food1?=?cartItem.getFoodBean();
//?定義int類型變量quantity,用于表示購物車中單個餐品的數(shù)量
int?quantity?=?cartItem.getQuantity();
//?定義double變量price,表示餐品單價
double?price?=?food1.getFoodPrice();
//?定義double變量,subtotal表示單個餐品總價
double?subtotal?=?quantity?*?price;
//?//?計算購物車內(nèi)餐品總價格
total?+=?subtotal;
cartItem.setSubtotal(subtotal);
cartItem.setTotal(total);
list.add(cartItem);
}
return?list;
}
/**
*?增加訂餐
*/
public?Map?add(Map?cart,?String?foodID)?{
//?購物車為空
if?(cart?==?null)?{
cart?=?new?HashMap();
}
FoodModel?fd?=?new?FoodModel(conn);
FoodBean?food?=?fd.findFoodById(foodID);
//?判斷購物車是否放東西(第一次點餐)
if?(cart.isEmpty())?{
CartItemBean?cartBean?=?new?CartItemBean(food,?1);
cart.put(foodID,?cartBean);
}?else?{
//?判斷當(dāng)前菜是否在購物車中,false表示當(dāng)前菜沒有被點過。。
boolean?flag?=?false;
//?得到鍵的集合
Set?set?=?cart.keySet();
//?遍歷集合
Object[]?obj?=?set.toArray();
for?(int?i?=?0;?i??obj.length;?i++)?{
Object?object?=?obj[i];
//?如果購物車已經(jīng)存在當(dāng)前菜,數(shù)量+1
if?(object.equals(foodID))?{
int?quantity?=?((CartItemBean)?cart.get(object))
.getQuantity();
quantity?+=?1;
System.out.println(quantity);
((CartItemBean)?cart.get(object)).setQuantity(quantity);
flag?=?true;
break;
}
}
if?(flag?==?false)?{
//?把當(dāng)前菜放到購物車?yán)锩?/p>
CartItemBean?cartBean?=?new?CartItemBean(food,?1);
cart.put(foodID,?cartBean);
}
}
return?cart;
}
/**
*?取消訂餐
*/
public?Map?remove(Map?cart,?String?foodID)?{
cart.remove(foodID);
return?cart;
}
/**
*?更新購物車信息
*?
*?@param?cart
*?@param?foodID
*?@return
*/
public?MapString,?CartItemBean?update(Map?cart,?String?foodID,
boolean?isAddorRemove)?{
Map?map;
if?(isAddorRemove)?{
map?=?add(cart,?foodID);
}?else?{
map?=?remove(cart,?foodID);
}
return?map;
}
}
文章標(biāo)題:電商購物車java代碼 電商購物車java代碼是多少
文章出自:http://chinadenli.net/article32/doddssc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站收錄、Google、App開發(fā)、定制開發(fā)、品牌網(wǎng)站制作、軟件開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)