PageUtil

Origin

Pagination tool class is not a wrapper for database pagination, but a conversion between different pagination formats. When we manually paginate, we often use the page number and the number of items per page. However, some databases require the use of starting and ending positions to represent pagination. This conversion is error-prone (especially with boundary issues) and hence the wrapper of PageUtil tool class.

Usage

transToStartEnd

Converts page number and items per page to starting and ending positions. This method is for pagination methods that do not include the ending position.

Example:

  • Page number: 0, items per page: 10 -> [0, 10]
  • Page number: 1, items per page: 10 -> [10, 20]
int[] startEnd1 = PageUtil.transToStartEnd(0, 10); // [0, 10]
int[] startEnd2 = PageUtil.transToStartEnd(1, 10); // [10, 20]

In this method, page numbers start from 0 and positions start from 0 as well.

totalPage

Calculates the total number of pages based on the total number of items and the number of items per page.

int totalPage = PageUtil.totalPage(20, 3); // 7

Pagination Rainbow Algorithm

This method is from: https://github.com/iceroot/iceroot/blob/master/src/main/java/com/icexxx/util/IceUtil.java

When showing the next page on a webpage, it is often necessary to display the previous N pages and the next N pages. The PageUtil.rainbow is designed for this purpose.

For example, if we are currently on page 5 and there are 20 total pages, with only 6 pages displayed per screen, the pagination list should be displayed as follows:

Previous page 3 4 [5] 6 7 8 Next page
// Parameters: current page, total pages, number of pages displayed per screen
int[] rainbow = PageUtil.rainbow(5, 20, 6);
// Result: [3, 4, 5, 6, 7, 8]