JSP 网站建设 分页技巧

在BBS论坛中常用到分页,自己总结的分页技巧如下:


<%
final int PAGE_SIZE = 4;//定义每页要显示的页数为一个final变量
int pageNo = 1;
String strPageNo = request.getParameter("pageNo");//拿到传到本页面的pageNo
//对pageNo 进行判断
if(strPageNo != null && !strPageNo.trim().equals("")) {
    try {
        pageNo = Integer.parseInt(strPageNo);//用Integer包装类把strPageno 转化为int 类型
    } catch (NumberFormatException e) {
        pageNo = 1;
    }
}
if(pageNo <= 0) pageNo = 1;//对pageNo小于0的情况进行判断
//int totalPages;//给总页面数一个初值
List<Article> articles = new ArrayList<Article>();//new 一个list容器装数据
Connection conn = DB.getConn();//拿到链接
Statement stmtCount = DB.createStmt(conn);//拿到Statement
ResultSet rsCount = DB.executeQuery(stmtCount, "select count(*) from article where pid = 0");//因为是平板型展现,从数据库中取出pid为0的帖子
rsCount.next();//遍历
int totalRecords = rsCount.getInt(1);//
//第一种计算所有页数的方法
//totalPages = (totalRecords + PAGE_SIZE - 1)/PAGE_SIZE;
//算出所有的页数(第二种方法)
int  totalPages = totalRecords % PAGE_SIZE == 0 ? totalRecords/ PAGE_SIZE : totalRecords / PAGE_SIZE + 1;/
if(pageNo > totalPages) pageNo = totalPages;//如果页号比总页数要少,把总页数赋给页号
Statement stmt = DB.createStmt(conn);
int startPos = (pageNo-1) * PAGE_SIZE; //起始位置为页数-1后再乘以每页要显示的页数
String sql = "select * from article where pid = 0 order by pdate desc limit " + startPos + "," + PAGE_SIZE ;
System.out.println(sql);
ResultSet rs = DB.executeQuery(stmt, sql);
while(rs.next()) {
    Article a = new Article();
    a.initFromRs(rs);
    articles.add(a);
}
DB.close(rsCount);
DB.close(stmtCount);
DB.close(rs);
DB.close(stmt);
DB.close(conn);
%>


你可能感兴趣的:(技巧,网站建设,网站分页)