这里分两步给大家展示:
1.分页代码(注:连接数据库的,查询返回的结果集需要自己写,这个分页面是对结果集进行处理,返回一个当前页面的一个子记录,回传到JSP页面)
package com.hy.ly.utils;
import java.util.List;
public class Pager<T> {
private Pager() {
}
//每页记录数
private int recordsOfPerPage = 5;
//当前页
private int currentPage;
//总记录数
private int totalRecords;
//总页数
private int totalPages;
//查询的当前页记录列表
private List<T> list;
private int getRecordsOfPerPage() {
return recordsOfPerPage;
}
private void setRecordsOfPerPage(int recordsOfPerPage) {
this.recordsOfPerPage = recordsOfPerPage;
}
private int getCurrentPage() {
return currentPage;
}
//当前页面小于等于1时,设置当前页面为1;当前页面大于等于最大页面时,设置当前页面为最大页面。
private void setCurrentPage(int currentPage) {
this.currentPage = currentPage <= 1 ? 1
: currentPage >= this.totalPages ? this.totalPages
: currentPage;
}
private int getTotalRecords() {
return totalRecords;
}
private void setTotalRecords(int totalRecords) {
this.totalRecords = totalRecords;
}
private int getTotalPages() {
return totalPages;
}
//设置总页面数:总页数=总记录数/每页记录数(整除),总页数=总记录数/每页记录数+1(未整除),
private void setTotalPages() {
this.totalPages = this.getTotalRecords() % this.getRecordsOfPerPage() == 0 ? this
.getTotalRecords() / this.getRecordsOfPerPage()
: this.getTotalRecords() / this.getRecordsOfPerPage() + 1;
}
private List<T> getList() {
return list;
}
private void setList(List<T> list) {
this.list = list;
}
//固定每页记录的数的分页方法,见默认值:5
public List<T> queryPage(int currentPage,List<T> list){
setTotalRecords(list.size());
setTotalPages();
setCurrentPage(currentPage);
if(this.getCurrentPage()==this.getTotalPages()){
this.setList(list.subList((this.getCurrentPage()-1)*this.getRecordsOfPerPage(), this.getTotalRecords()));
}else{
this.setList(list.subList((this.getCurrentPage()-1)*this.getRecordsOfPerPage(), this.getCurrentPage()*this.getRecordsOfPerPage()));
}
return this.getList();
}
//可以设置每页记录的数的分页方法
public List<T> queryPage(int currentPage,int recordsOfPerPage,List<T> list){
setTotalRecords(list.size());
setRecordsOfPerPage(recordsOfPerPage);
setTotalPages();
setCurrentPage(currentPage);
if(this.getCurrentPage()==this.getTotalPages()){
this.setList(list.subList((this.getCurrentPage()-1)*this.getRecordsOfPerPage(), this.getTotalRecords()));
}else{
this.setList(list.subList((this.getCurrentPage()-1)*this.getRecordsOfPerPage(), this.getCurrentPage()*this.getRecordsOfPerPage()));
}
return this.getList();
}
//这里把分页设置成单例模式,当前项目只能实例化一个Pager对象。
@SuppressWarnings("rawtypes")
private static final Pager pager=new Pager<>();
@SuppressWarnings("rawtypes")
public static Pager getPager(){
return pager;
}
}
2.如何调用(这里只是用单元测试进行验证)
public void testQueryStu() {
String sql = "select * from student";
List<Student> list = DBUtils.executeQuery2(Student.class, sql, null); //数据库返回记录集
@SuppressWarnings("unchecked")
Pager<Student> pager = Pager.getPager();
//输入当前页6,返回第6页面内容的一个子表表,subList 传到前端JSP进行显示
List<Student> subList = pager.queryPage(6, list);
for (Student stu : subList) {
System.out.println(stu);
}
}