java 原生分页

来源:互联网 发布:魅族m9软件 编辑:程序博客网 时间:2024/05/30 04:54

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;
}
原创粉丝点击