本文實例為大家分享了新聞列表分頁查詢的java代碼,供大家參考,具體內容如下
package com.ibeifeng.test;//創建新聞測試類public class newTest {private long id;private String title;private String content;private String author; public newTest() { super();} public newTest(long id, String title, String content, String author) { this.id = id; this.title = title; this.content = content; this.author = author;} public long getId() { return id;} public void setId(long id) { this.id = id;} public String getTitle() { return title;} public void setTitle(String title) { this.title = title;} public String getContent() { return content;} public void setContent(String content) { this.content = content;} public String getAuthor() { return author;} public void setAuthor(String author) { this.author = author;} @Overridepublic String toString() { return "newTest [id=" + id + ",, content=" + content + ", author=" + author + "]";} }2.開始查詢<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@ page import="com.ibeifeng.test.newTest"%><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%><% List<newTest> list = new ArrayList<newTest>(107);//設定新聞行數為107行for (int i = 1; i <= 107; i++) {//list中添加新聞newTest news = new newTest(0L + i, i + "里約奧運", "馬龍獲得金牌-世界乒壇第五位男子“大滿貫”得主", "福音"); list.add(news); }//end of for...添加107條數據到集合中//int pageIndex=10; int iTitleIndex = list.size();//獲取集合下表標int iTitlePages = iTitleIndex / 10 + (iTitleIndex % 10 == 0 ? 0 : 1);//獲取頁數的總數int ipage = 4;//開始的頁數String str = request.getParameter("page"); if (str != null && !str.trim().equals("")) { int newPage = Integer.valueOf(str); if (newPage < 1) { ipage = 1; } else if (newPage > iTitlePages) { ipage = iTitlePages; } else { ipage = newPage; } } //創建一個新的集合(大小每個頁面顯示的新聞總數) 將107條數據分別存儲到其中List<newTest> listPage = new ArrayList<newTest>(10); int ipa = 10;//獲取循環體的循環次數//最後一頁只有七條數據if (ipage == iTitlePages) { //噹噹前頁數為最後一頁時,剩餘幾行則循環體之執行剩餘的行的數次, ipa = list.size() - (iTitlePages - 1) * 10; } for (int i = 0; i < ipa; i++) { //i=0;獲取前十個數據第一次循環時ipage=4 newTest arr = list.get(i + (ipage - 1) * 10); listPage.add(arr); }%><html><body> <table> <tr> <th>標題</th> <td>作者</td> <td>摘要</td> </tr> <% for (int i = 0; i < listPage.size(); i++) { //java代碼需要用<% %》保護起來否則會被當做web語句執行newTest temp = listPage.get(i); %> <tr> <td><%=temp.getTitle()%></td> <td><%=temp.getAuthor()%></td> <td><%=temp.getContent()%></td> </tr> <% }//end of for... %> </table> <% boolean bFirst = ipage == 1; boolean bLast = ipage == iTitlePages ; %> <% if (!bFirst) { %> <a href="test.jsp?page=<%=ipage - 1%>&totopage=11">上一頁</a> <% } %> <!-- 當跳轉到第一頁時不再顯示“上一頁”提交對話框,下同--> <% if (!bLast) { %> <a href="test.jsp?page=<%=ipage + 1%>&totopage=11">下一頁</a> <% } %>第<%=ipage%>頁共<%=iTitlePages%>頁</body></html>以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。