我正在使用 java servlet 和 oracle 11g
我正在研究分页,代码已大致完成,但问题是控制显示页码:
[![请参阅此示例图片][1]][1]
这是我的代码:
PreparedStatement ps1 = null;
ResultSet rs2 = null;
ps1 = con.prepareStatement("select count(*) from country");
rs2 = ps1.executeQuery();
if(rs2.next()) {
totalNumberOfRecords = rs2.getInt(1);
}
rs2.close();
numberOfPages = totalNumberOfRecords / recordPerPage;
if (totalNumberOfRecords > numberOfPages * recordPerPage) {
numberOfPages = numberOfPages + 1;
}
// display hyperlinks for each page to view the records
for (int k = 1; k <= numberOfPages; k++) {
pw.println("<b><a href=ps?pageno=" + k + ">" + k + "</a></b>");
pw.println(" ");
}
此代码正在打印所有页面,而我试图仅打印 5 页,例如:
1 2 3 4 5
,当单击第 6 条记录时,它会显示 6 7 8 9 10
请帮助我 [1]:https://i.sstatic.net/v8Sn5xo7.png
为了控制分页显示页码的区块(例如一次只显示5个页码),可以增强逻辑,根据当前页面动态计算显示的页码范围。试试这个代码:
// Number of records per page
int recordPerPage = 10; // Adjust as needed
// Get total number of records
PreparedStatement ps1 = null;
ResultSet rs2 = null;
ps1 = con.prepareStatement("SELECT COUNT(*) FROM country");
rs2 = ps1.executeQuery();
int totalNumberOfRecords = 0;
if (rs2.next()) {
totalNumberOfRecords = rs2.getInt(1);
}
rs2.close();
// Calculate the total number of pages
int numberOfPages = totalNumberOfRecords / recordPerPage;
if (totalNumberOfRecords > numberOfPages * recordPerPage) {
numberOfPages += 1;
}
// Get the current page number from request parameters (default to 1)
int currentPage = 1;
String pageParam = request.getParameter("pageno");
if (pageParam != null) {
currentPage = Integer.parseInt(pageParam);
}
// Define the range of pages to display (e.g., 5 pages at a time)
int pagesToShow = 5;
int startPage = Math.max(1, currentPage - pagesToShow / 2);
int endPage = Math.min(startPage + pagesToShow - 1, numberOfPages);
// Adjust startPage if near the end of the total pages
if (endPage - startPage + 1 < pagesToShow) {
startPage = Math.max(1, endPage - pagesToShow + 1);
}
// Display page numbers in the block
for (int k = startPage; k <= endPage; k++) {
if (k == currentPage) {
pw.println("<b>" + k + "</b>");
} else {
pw.println("<b><a href='ps?pageno=" + k + "'>" + k + "</a></b>");
}
pw.println(" ");
}
// Display "Previous" and "Next" links
if (currentPage > 1) {
pw.println("<a href='ps?pageno=" + (currentPage - 1) + "'>Previous</a> ");
}
if (currentPage < numberOfPages) {
pw.println("<a href='ps?pageno=" + (currentPage + 1) + "'>Next</a>");
}
解释
startPage
是动态计算的,因此
块是当前页面(currentPage - pagesToShow / 2
)。endPage
确保我们不会超出总数量
页面,并相应调整 startPage
。pagesToShow
(例如 5)页码的块
当前页面。