分层:也就是开发模式分三层(数据访问层,业务逻辑层,视图层)
代码文件解析
entity:实体类 util:帮助类
dao:数据访问层接口类 dao.imp:数据访问层实现接口类
biz:业务逻辑层接口类 biz.imp:业务逻辑层实现接口类
创建项目,在Java Resources中写分层的代码,分为6个包,在购物车1.0版本中就提及到entity和util包的作用。但购物车2.0版本要符合开发模式,并且实现分层,dao类中用接口,定义方法,dao.imp中实现(implements)方法。biz中再用接口定义方法,biz.imp实现方法,同时在biz.imp中调用数据访问层的方法
代码如下:
1.实体类和帮助类参考购物1.0系统
2.dao和dao.imp的代码
dao中(以商品表举例)
/**
* 商品数据访问层的接口类
* @author zjjt
*
*/
public interface IGoodsDao {
/**
* 查询所有商品
* @return 返回商品集合
*/
public ArrayList<Goods> getAll();
/**
* 根据商品编号查询
* @param bid 商品编号
* @return 返回商品对象
*/
public Goods getById(int bid);
}
dao.imp
/**
* 查询商品集合
*/
public ArrayList<Goods> getAll() {
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
ArrayList<Goods> alist=new ArrayList<>();
try {
con=DBHelper.getCon();
ps=con.prepareStatement("select * from goods");
rs=ps.executeQuery();
while(rs.next()) {
alist.add(new Goods(rs.getInt(1), rs.getString(2), rs.getDouble(3), rs.getString(4), rs.getString(5)));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.closeDb(con, ps, rs);
}
return alist;
}
/**
* 根据商品编号查询
*/
public Goods getById(int bid) {
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
Goods go=null;
try {
con=DBHelper.getCon();
ps=con.prepareStatement("select * from goods");
rs=ps.executeQuery();
while(rs.next()) {
go=new Goods(bid, rs.getString(2), rs.getDouble(3), rs.getString(4), rs.getString(5));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.closeDb(con, ps, rs);
}
return go;
}
3.biz和biz.imp
biz中
public interface IGoodsBiz {
/**
* 查询所有商品
* @return 返回商品集合
*/
public ArrayList<Goods> getAll();
/**
* 根据商品编号查询
* @param bid 商品编号
* @return 返回商品对象
*/
public Goods getById(int bid);
}
biz.imp中
public class Imp_GoodsBiz implements IGoodsBiz {
IGoodsDao id=new Imp_GoodsDao();
@Override
public ArrayList<Goods> getAll() {
// TODO Auto-generated method stub
return id.getAll();
}
@Override
public Goods getById(int bid) {
// TODO Auto-generated method stub
return id.getById(bid);
}
}
操作页面效果和购物1.0一样,不同点在于一个用户登入后只能查看他个人的购物车,不能查看别人的。