欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java商城购物车实现代码,java商城购物车,package com.

来源: javaer 分享于  点击 35828 次 点评:253

Java商城购物车实现代码,java商城购物车,package com.


package com.xxx.service.impl;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import com.xxx.dao.CartDAO;import com.xxx.dao.impl.JdbcCartDAO;import com.xxx.entity.CartItem;import com.xxx.entity.Product;import com.xxx.service.CartService;public class CartServiceImpl implements CartService{    List<CartItem> items = new ArrayList<CartItem>();    //增加商品    public boolean add(int id) throws SQLException {        for(CartItem item: items) {            if(item.getPro().getId() == id) {                                     //判断是否购买过                if(item.isBuy()) {                    item.setQty(item.getQty()+1);                    return true;                }            }            return false;//数据库出现错误,没有该商品        }        CartItem item = new CartItem();        CartDAO dao = new JdbcCartDAO();        Product pro = dao.findById(id);        item.setPro(pro);        item.setQty(1);        item.setBuy(true);        return true;    }    //删除商品    public void delete(int id) throws SQLException {        for(CartItem item: items) {            if(item.getPro().getId() == id) {                item.setBuy(false);            }        }    }    //恢复删除的商品    public void recovery(int id) throws SQLException {        for(CartItem item: items) {            if(item.getPro().getId() == id) {                item.setBuy(true);            }        }    }    //更新商品数量    public void update(int id, int pnum) throws SQLException {        for(CartItem item: items) {            if(item.getPro().getId() == id) {                if(item.getQty() == 0) {                    delete(id);                } else {                    item.setQty(pnum);                }            }        }    }    //获取购买过的商品    public List<CartItem> getBuyPros() throws SQLException {        List<CartItem> list = new ArrayList<CartItem>();        for(CartItem item: items) {            if(item.isBuy()) {                list.add(item);            }        }        if(list.size() > 0) {            return list;        }        return null;    }    //获取已经删除的商品(可以恢复)    public List<CartItem> getDelPros() throws SQLException {        List<CartItem> list = new ArrayList<CartItem>();        for(CartItem item: items) {            if(!item.isBuy()) {                list.add(item);            }        }        if(list.size() > 0) {            return list;        }        return null;    }    //商品消费总额    public double cost() throws SQLException {        double total = 0;        for(CartItem item: items) {            if(item.isBuy()) {                total += item.getQty()*item.getPro().getPrice();            }        }        return total;    }    //清空购物车    public void clear() throws Exception {        items.clear();    }}   
相关栏目:

用户点评