Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
Eight posts, three to a page, newest first. HomeController turns ?page=1&sort=oldest into a PageRequest, PostService passes it to findAll(Pageable), H2 runs one select with an offset and one count, and the Page that comes back knows it is page 2 of 3.
What you will learn
- Build a PageRequest from page and sort request parameters
- Get a Page of posts from findAll(Pageable) with no repository change
- Read the two SQL statements one page costs: a select with offset and a count
- Render newest/oldest links, page numbers and Previous/Next that keep the sort
Before you start
- Seed Data and Posts on the Homepage
Until now the homepage called getAll and showed every post on one long page. Seed data now makes eight posts, so we cut them into pages of three, newest first: page one has three, page two has three, page three has the last two.
Think of a book
You don't carry the whole book. You ask for the second page, three posts a page, newest first, and you get that page plus a footer that says "page 2 of 3". In Spring Data, the question is a PageRequest and the answer is a Page of posts.
PageRequest.of(1, 3, Sort.by(DESC, "publishedOn")) is page 1, size 3; from those Spring works out the offset, 1 times 3, so skip three posts. The Page that comes back holds the three posts as its content, its number (1), and the totals: 8 elements, so 3 pages. One trap: pages count from zero, so ?page=1 in the URL is the second page.
HomeController: which page, which order
@GetMapping("/")
public String home(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "newest") String sort, Model model) {
Sort.Direction direction = sort.equals("oldest") ? Sort.Direction.ASC : Sort.Direction.DESC;
PageRequest request = PageRequest.of(Math.max(page, 0), PAGE_SIZE, Sort.by(direction, "publishedOn"));
model.addAttribute("posts", postService.getPage(request));
model.addAttribute("sort", direction == Sort.Direction.ASC ? "oldest" : "newest");
return "home";
}
Both request parameters have defaults: page 0 and "newest". "oldest" means ascending; anything else is descending. Math.max(page, 0) keeps the page at zero or more, and PAGE_SIZE is 3. The sort goes into the Model too, so every link on the page can carry it.
PostService: one new method
public Page<Post> getPage(Pageable pageable) {
return postRepository.findAll(pageable);
}
PostRepository didn't change at all: findAll(Pageable) comes free with JpaRepository. The old getAll stays, because SeedData still uses it.
Two queries for one page
For ?page=1, Hibernate prints a select with order by ... published_on desc (from our Sort.by) followed by offset ? rows fetch first ? rows only: skip three, take three. Then a second query, select count(...) from post, returns 8, and 8 divided by 3 rounded up is 3 pages. That's where "page 2 of 3" comes from. With sort=oldest, the same select has no desc.
home.html: the links
<p class="sort-links">
<a th:href="@{/(sort='newest')}" th:classappend="${sort == 'newest'} ? 'current'">Newest</a>
<a th:href="@{/(sort='oldest')}" th:classappend="${sort == 'oldest'} ? 'current'">Oldest</a>
</p>
</div>
<p class="empty-page" th:if="${posts.isEmpty()}">
No posts on this page. <a class="text-link" th:href="@{/(sort=${sort})}">Back to page 1</a>
</p>
<div class="post-grid">
<th:block th:each="post : ${posts}">
<div th:replace="~{fragments/layout :: postCard(${post.title}, ${post.category},
${#temporals.format(post.publishedOn, 'MMMM d, yyyy')}, ${post.excerpt},
@{/posts/{id}(id=${post.id})})}"></div>
</th:block>
</div>
<nav class="pager" aria-label="Pages" th:if="${posts.totalPages > 1 and !posts.isEmpty()}">
<a th:if="${posts.hasPrevious()}" th:href="@{/(page=${posts.number - 1}, sort=${sort})}">Previous</a>
<a th:each="i : ${#numbers.sequence(0, posts.totalPages - 1)}" th:href="@{/(page=${i}, sort=${sort})}"
th:text="${i + 1}" th:classappend="${i == posts.number} ? 'current'">1</a>
<a th:if="${posts.hasNext()}" th:href="@{/(page=${posts.number + 1}, sort=${sort})}">Next</a>
<span class="pager-info" th:text="|Page ${posts.number + 1} of ${posts.totalPages}|">Page 1 of 3</span>
</nav>
Two links at the top switch between Newest and Oldest, and the current one is highlighted. th:each loops over the Page, which iterates over the posts inside it. Under the cards come Previous, the page numbers from 0 to totalPages - 1 shown as i + 1, and Next. Every link carries the sort, so oldest stays oldest. The URL counts from zero; the label counts from one.
Page 2, oldest first, and pages that don't exist
Plain / is page one of three, with only Next. ?page=1 shows the fourth, fifth and sixth newest posts with Previous and Next. ?sort=oldest starts with "Ask better questions" from 16 April, the oldest post in the seed data. ?page=9 doesn't exist, so the Page comes back empty and the template says "No posts on this page" with a link back to page 1. ?page=-1 is turned into page 0 by Math.max. No error pages: an empty page and a way back.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
A one-line JpaRepository interface and a small @Service class save and read blog posts with no SQL. Follow one save and one read through every layer, then prove it with a test.
Entities and H2 in Spring Boot: a Post Class Becomes a Table
The blog's cards are typed into HTML. A Post class with @Entity and @Id becomes the POST table in an in-memory H2 database: three pom lines, a few YAML settings, and Hibernate writes the create table SQL at startup.
Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
SeedData, a CommandLineRunner, saves three posts when the POST table is empty. HomeController puts postService.getAll() into the Model, and one postCard inside th:each becomes three cards. Three inserts at startup, one select per visit.
Connect Spring Boot to PostgreSQL: Driver, application.yml and the Hikari Pool
Connect the Relay support desk to PostgreSQL 18: one compose service, one driver line in the pom, a datasource in application.yml with a strict prod profile, and a small runner that asks the server who it is through the Hikari pool.
