Javaコードでページング機能を実装する方法はどのようになりますか?
以下はページネーション機能を実装したJavaコードの例です。
public class Pagination {
private int currentPage;
private int pageSize;
private int totalRecords;
public Pagination(int currentPage, int pageSize, int totalRecords) {
this.currentPage = currentPage;
this.pageSize = pageSize;
this.totalRecords = totalRecords;
}
public int getTotalPages() {
return (int) Math.ceil((double) totalRecords / pageSize);
}
public int getStartIndex() {
return (currentPage - 1) * pageSize;
}
public int getEndIndex() {
return Math.min(currentPage * pageSize, totalRecords);
}
}
使用時、総レコード数、現在のページ番号、およびページごとのレコード数をコンストラクタに渡し、getTotalPagesメソッドを使用して総ページ数を取得し、getStartIndexおよびgetEndIndexメソッドを使用して現在のページに表示されているレコードの開始インデックスと終了インデックスを取得します。
使用例:
public class Main {
public static void main(String[] args) {
int currentPage = 2;
int pageSize = 10;
int totalRecords = 37;
Pagination pagination = new Pagination(currentPage, pageSize, totalRecords);
int totalPages = pagination.getTotalPages();
int startIndex = pagination.getStartIndex();
int endIndex = pagination.getEndIndex();
System.out.println("总页数:" + totalPages);
System.out.println("起始索引:" + startIndex);
System.out.println("结束索引:" + endIndex);
}
}
実行結果:
总页数:4
起始索引:10
结束索引:20
この例では、合計レコード数は37で、1ページに表示されるレコード数は10で、現在のページは2ページ目です。したがって、合計ページ数は4で、現在のページの開始インデックスは10で終了インデックスは20になります。