java 原生分页

public class PageServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String dang1 = req.getParameter("dang");
if(dang1==null) {
dang1 = "1";
}
Integer dang = Integer.valueOf(dang1);

ProService ps = new ProService();
int count = ps.queryCount();
int totalPage = 1;
if(count%3==0) {
totalPage = count/3;
}else {
totalPage = count/3+1;
}
Page p = new Page(3, count, totalPage, dang);

List<Product> list = ps.queryAll(p);

HttpSession session = req.getSession();
session.setAttribute("proList", list);
session.setAttribute("page", p);
resp.sendRedirect("index.jsp");
}
}


public class ProService {


public int queryCount() {
Connection conn = ConnectionFactory.getConnection();
String sql = "select count(*) from product";
PreparedStatement ps;
int count = 0;
try {
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
count = rs.getInt(1);
}

} catch (SQLException e) {
e.printStackTrace();
}

return count;
}

public List<Product> queryAll(Page p) {
List<Product> list =new ArrayList<>();
Connection conn = ConnectionFactory.getConnection();
String sql = "select p.* from(select rownum as rn,id,name,price,count from product)p where rn > ? and rn <= ? ";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, p.getShow()*(p.getDang()-1));
ps.setInt(2, p.getShow()*p.getDang());
ResultSet rs = ps.executeQuery();
while(rs.next()) {
long id = rs.getLong("id");
String name = rs.getString("name");
int count = rs.getInt("count");
int price = rs.getInt("price");
Product pro = new Product(id, name, price, count);
list.add(pro);
}
} catch (SQLException e) {
e.printStackTrace();
}

return list;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值