一个简单的JAVA分页展示
这里是实现类:
public class PageUtilServices {
private int pageSize;//每页显示的条数
private int recordCount;//总共的条数
private int currentPage;//当前页面
//构造方法
public PageUtilServices(int pageSize, int recordCount, int currentPage) {
super();
this.pageSize = pageSize;
this.recordCount = recordCount;
this.currentPage = currentPage;
}
public PageUtilServices() {
super();
}
//总页数
public int getPageCount() {
int size = recordCount/pageSize;//总条数/每页显示的条数=总页数
int mod = recordCount % pageSize;//最后一页的条数
if(mod != 0)
size++;
return recordCount == 0 ? 1 : size;
}
//当前页的起始索引为0
public int getFromIndex() {
return (currentPage-1) * pageSize;
}
//当前页应展示的最后索引
public int getToIndex() {
return Math.min(recordCount, currentPage * pageSize);
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getRecordCount() {
return recordCount;
}
public void setRecordCount(int recordCount) {
this.recordCount = recordCount;
}
}
这里是写在JSP前面的代码:
BookInfoDao dao = new BookInfoDao();
List<Books> bookList = dao.showBooks();
String pageStr = request.getParameter("page");
int currentPage = 1;
if (pageStr==null){
currentPage = 1;
}else if(Integer.parseInt(pageStr)<=0){
currentPage = 1;
}else if(Integer.parseInt(pageStr)>bookList.size()/3){
currentPage =bookList.size()/3+1;
}else{
currentPage=Integer.parseInt(pageStr);
}
PageUtilServices pUtil = new PageUtilServices(3, bookList.size(), currentPage);
currentPage = pUtil.getCurrentPage();
这里是中间循环的代码:
for (int i = pUtil.getFromIndex(); i < pUtil.getToIndex(); i++) {
}
这里是最后部分的代码:
<tr><td colspan=13 align="center">
记录总数<%=pUtil.getRecordCount()%>条 当前页/总页数<%=currentPage%>
/<%=pUtil.getPageCount()%> 每页显示<%=pUtil.getPageSize()%>条
<a href="booklist.jsp?page=1">首页</a>
<a href="booklist.jsp?page=<%=(currentPage - 1)%>">上页</a>
<a href="booklist.jsp?page=<%=(currentPage + 1)%>">下页</a>
<a href="booklist.jsp?page=<%=pUtil.getPageCount()%>">末页</a>
</td>
</tr>