日期:2014-05-16  浏览次数:20593 次

JDBC分页实现
   对于一个页面数据记录显示过多时候,那就只有对获取到得数据库所有记录放到集合传递给页面进行上一页下一页的效果,也是为了防治给客户数据过多带来的不必要的麻烦。。。。。
   下面是一些代码:
(存储过程也可以实现)
StudentDAO:
/**
* 根据页面长度和页码在数据库中查询出对应的信息
*/
public List<StudentDTO> list(int pageSize,int pageNum){
List<StudentDTO> stus = new ArrayList<StudentDTO>();
try {
conn = DBManager.getConn();
String sql = "select top(?) * from tb_stu where stu_num not in(select top(?) stu_num from tb_stu)";
ps = conn.prepareStatement(sql);
ps.setInt(1, pageSize);
ps.setInt(2, pageSize*(pageNum-1));
rs = ps.executeQuery();
while(rs.next()){
String num = rs.getString("stu_num");
String name = rs.getString("stu_name");
String sex = rs.getString("stu_sex");
int age = rs.getInt("stu_age");
String department = rs.getString("stu_department");
String sclass = rs.getString("stu_class");
String pid = rs.getString("stu_pid");
String des = rs.getString("stu_des");
StudentDTO stu = new StudentDTO(num,name,sex,age,department,sclass,pid,des);
stus.add(stu);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
DBManager.close(rs, s, conn);
}
return stus;
}
/**
* 根据页面长度,获取总页数
* @param pageSize
* @return
*/
public int getTotalPage(int pageSize){
int pageCount = 0;
try {
conn = DBManager.getConn();
String sql = "select count(*) from tb_stu";
s = conn.createStatement();
rs = s.executeQuery(sql);
if(rs.next()){
int count = rs.getInt(1);
pageCount = count%pageSize==0?count/pageSize:count/pageSize+1;
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
DBManager.close(rs, s, conn);
}
return pageCount;
}
ListStuServlet(doPost):
servlet相应页面请求,这里对页面的上下页功能我理解为函数回调一样。。。。
int pageSize = 10;
int pageNum = 1;
//点击下一页,接收到下一页的页码
String nextPage = request.getParameter("pageNum");
if(nextPage!=null){
pageNum = Integer.parseInt(nextPage);
}
//查询到所有的学生信息
List<StudentDTO> stus = new StudentDAO().list(pageSize,pageNum);
//获取总页面
int pageCount = new StudentDAO().getTotalPage(pageSize);
//传递到show页面进行显示
request.setAttribute("stus", stus);
//把当前页和总页数传递到页面
request.setAttribute("nowPage", pageNum);
request.setAttribute("pageCount", pageCount);
request.getRequestDispatcher("show.jsp").forward(request, response);
页面中的分页标签:(关键代码)
<c:if test="${nowPage eq 1}">
<font color="gray">首页 </font>
<font color="gray">上一页</font>
</c:if>
<c:if test="${nowPage>1}">
首页
[url=ListStuServlet?pageNum=${nowPage-1 }]上一页[/url]
</c:if>

<c:if test="${nowPage < pageCount}">
[url=ListStuServlet?pageNum=${nowPage+1 }]下一页[/url]
[url=ListStuServlet?pageNum=${pageCount }]尾页[/url]
</c:if>
<c:if test="${nowPage eq pageCount}">
<font color="gray">下一页 </font>
<font color="gray">尾页</font>
</c:if>
当前第${nowPage }页/共${pageCount }页