在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); %>