三层架构是每个公司都有要求的,根据我的理解,由表示层(jsp)->业务逻辑层(biz包)->数据访问层(dao包),jsp主要用于页面的显示,biz包用于接口写方法,dao包用于接口写方法,最开始写dao包的接口,也就是你需要对数据库进行操作的方法,biz随后写,和dao包的方法一样,还可在里面进行其他操作,最后是impl实现接口的包,都是class,先实现dao包的接口,在里面写对数据库操作语句实现方法,实现biz包的方法时,调用实现了的dao方法,但要以接口名进行里式替换,返回对应值。
dao包接口代码展示
package dao;
import java.util.List;
import pojo.Goods;
public interface IGoodsDao {
List<Goods> list(int page,int size);
public int total();
}
biz包接口代码展示
package biz;
import java.util.List;
import pojo.Goods;
public interface IGoodsBiz {
List<Goods> list(int page,int size);
public int total();
}
impl包实现类代码展示
实现dao包
package impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import dao.IGoodsDao;
import pojo.Goods;
import util.DBHelper;
public class GoodsDaoImpl implements IGoodsDao{
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
@Override
public List<Goods> list(int page, int size) {
List<Goods> list=new ArrayList();
int begin=(page-1)*size+1;
int end=page*size;
try {
con=DBHelper.getCon();
ps=con.prepareStatement("select * from (" +
" select a.*,ROWNUM rid from BS_GOODS a" +
") temp where rid between ? and ?");
ps.setInt(1,begin);
ps.setInt(2,end);
rs= ps.executeQuery();
while(rs.next()){
Goods goods=new Goods();
goods.setId(rs.getInt(1));
goods.setName(rs.getString(2));
goods.setDescribe(rs.getString(3));
goods.setPrice(rs.getInt(4));
goods.setStock(rs.getInt(5));
goods.setCover(rs.getString(6));
list.add(goods);
}
}catch (Exception e){
e.printStackTrace();
}finally {
DBHelper.close(con,ps,rs);
}
return list;
}
@Override
public int total() {
try {
con=DBHelper.getCon();
ps=con.prepareStatement("select count(1) from bs_goods");
rs= ps.executeQuery();
if(rs.next()){
return rs.getInt(1);
}
}catch (Exception e){
e.printStackTrace();
}finally {
DBHelper.close(con,ps,rs);
}
return 0;
}
}
实现biz包
调用dao包的实现类返回值
package impl;
import biz.IGoodsBiz;
import dao.IGoodsDao;
import pojo.Goods;
import java.util.List;
public class GoodsBizImpl implements IGoodsBiz {
private IGoodsDao goodsDao=new GoodsDaoImpl();
@Override
public List<Goods> list(int page, int size) {
return goodsDao.list(page, size);
}
@Override
public int total() {
return goodsDao.total();
}
}
今天的分享就到这了