电商购物车java代码 电商购物车java代码是多少
编程 java 关于购物车
点击数量进入购物车页面,这个应该好做吧,跳动一个Action转发到购物车页面
创新互联建站专业为企业提供疏附网站建设、疏附做网站、疏附网站设计、疏附网站制作等企业网站建设、网页设计与制作、疏附企业网站模板建站服务,十载疏附做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
下面是我的图书购物车(自己写的)
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)//根据图书ID增加数量
{
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还要遍历。。。。。。
希望对你有帮助!!
java中写商品购物车怎么实现每种商品总价都随商品数量变化而变化??
以前学习java又做个实例,挺值得学习的。1.首先我先列出我们所需要的java类结构。1)Database.java---------模拟存储商品的数据库。2)McBean.java------------商品实体类,一个普通的javabean,里面有商品的基本属性。3)OrderItemBean.java---订单表。4)ShoppingCar.java------这个就是最主要的购物车,当然比较简单。5)TestShoppingCar.java---这个是测试类。2.下面贴出具体代码并带关键注释。---Database.javapublicclassDatabase{/*采用Map存储商品数据,为什么呢?我觉得这个问题你自己需要想下。*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;//购物车所有商品数量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购买数量\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("合计:总数量:"+df.format(totalCount)+"总价格:"+df.format(totalPrice));System.out.println("**********************************************");}}---OrderItemBean.javapublicclassOrderItemBean{privateMcBeanthing;//商品的实体privateintcount;//商品的数量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.打印输出结果商品编号商品名称单价购买数量总价1地瓜¥23¥62土豆¥1.21¥1.23丝瓜¥1.51¥1.5合计:总数量:¥5总价格:¥8.7**********************************************商品编号商品名称单价购买数量总价2土豆¥1.21¥1.23丝瓜¥1.51¥1.5合计:总数量:¥2总价格:¥2.7**********************************************商品编号商品名称单价购买数量总价合计:总数量:¥0总价格:¥0**********************************************4.打字太累了,比较匆忙,但是主要靠你自己领会。哪里不清楚再提出来。
java简单的购物车代码
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("还要继续购物吗?(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("请输入购买数量:");
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;
}
}
JAVA 购物车示例代码
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可能显示不出来你的效果。不满意得话我在给你编一个。
如何用java和jsp做一个简单的购物车
页面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易买网 - 首页/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"
您现在的位置:a href="Home"易买网/a gt; 购物车
/div
div class="wrap"
div id="shopping"
form action="" method="post"
table
tr
th商品名称/th
th商品价格/th
th购买数量/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 远标培训.
/div
/body
/html
页面关联的js 自己去网上下载一个jquery
/*数量减少*/
function sub(id,proId){
//购买数量的值
var num = $('#'+id).val();
if(num 1){
$('#'+id).val(num - 1);
}
edit(id,proId);
}
function edit(id,proId){
var url = contextPath + '/HomeCarManager';
//修改后的数量,购物明细的商品的id
num = $('#'+id).val();
$.post(url,{"num":num,"proId":proId},function (msg){
/*
if(msg == 'true'){
alert('修改成功');
} else {
alert('修改失败');
}*/
});
}
/**
* 数量增加
* @param {} id
*/
function addNum(id,proId){
//购买数量的值
var num = $('#'+id).val();
$('#'+id).val(parseInt(num) + 1);
edit(id,proId);
}
/**
* 删除购物明细
*/
function deleteItem(trId,proId){
//
//console.log($("#"+trId));
//js删除页面节点
//$("#"+trId).remove();
var url = contextPath + '/HomeCarManager';
$.post(url,{"proId":proId},function (msg){
if(msg == 'true'){
//js删除页面节点
$("#"+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 远标培训
*
*/
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);
//根据商品的id查询商品
try {
Integer pId = Integer.parseInt(proId);
Product product = ps.findProductById(pId);
if(null != product){
//查询到了商品,将商品的相关参数构建一个购物明细放入到购物车
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();
}
//将商品加入到购物车之前,判断购物车中是否已经包含了该购物明细,如果包含了,只需要修改购买的数量
if(shopCar.contains(it)){
int index = shopCar.indexOf(it);//寻找购物车中包含购物明细在购物车中位置
Items items = shopCar.get(index);//获取购物车中存在的购物明细
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 远标培训
*
*/
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();
//获取参数
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);
//根据商品的id获取对应的明细项
// 先判断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);
//根据商品的id获取对应的明细项
// 先判断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);
}
}
JAVA语言编写的网上订餐系统购物车功能如何实现?
用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中元素转换成数组,以便使用循环进行遍历
Object[] foodItems = carts.keySet().toArray();
// 定义double变量total,用于存放购物车内餐品总价格
double total = 0;
List list = new ArrayList();
// 循环遍历购物车内餐品,并显示各个餐品的餐品名称,价格,数量
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,用于表示购物车中单个餐品的数量
int quantity = cartItem.getQuantity();
// 定义double变量price,表示餐品单价
double price = food1.getFoodPrice();
// 定义double变量,subtotal表示单个餐品总价
double subtotal = quantity * price;
// // 计算购物车内餐品总价格
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 {
// 判断当前菜是否在购物车中,false表示当前菜没有被点过。。
boolean flag = false;
// 得到键的集合
Set set = cart.keySet();
// 遍历集合
Object[] obj = set.toArray();
for (int i = 0; i obj.length; i++) {
Object object = obj[i];
// 如果购物车已经存在当前菜,数量+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) {
// 把当前菜放到购物车里面
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;
}
}
文章题目:电商购物车java代码 电商购物车java代码是多少
URL标题:http://pwwzsj.com/article/doddssc.html