環境
名称 | バージョン |
---|---|
Spring Boot | 3.1.4 |
spring-boot-starter-data-jpa | 3.1.5 |
thymeleaf | 3.1.5 |
コード
元のコードから雑に書き換えているので間違っていたらsry。
TestController.java
@GetMapping(value = TEST_SEARCH)
public String showSearchPage(@Validated @ModelAttribute TestSearchConditionsForm conditionForm,
@RequestParam(name = "page", required = false, defaultValue = "0") int showPage,
@RequestParam(name = "size", required = false, defaultValue = "20") int showSize,
BindingResult bindingResult, Model model) {
// 中略
// ページネーションの設定
Pageable pageable = Pageable.ofSize(showSize).withPage(showPage);
// serviceでデータ取得
Page<TestForm> TestFormPage = service.searchTest(conditionForm, pageable);
// 中略
model.addAttribute("page", TestFormPage);
// 中略
}
main.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<!-- 中略 -->
</head>
<body>
<h1>検索</h1>
<!-- 検索条件 -->
<form th:action="@{/test_search}" th:object="${testSearchConditionsForm}" method="GET">
<!-- 中略 -->
</form>
<!-- 検索結果 -->
<p th:text="'検索結果:' + ${page.TotalElements} + '件'"></p>
<table id="search_result">
<tr>
<!-- 中略 -->
</tr>
<tr th:each="_r : ${page.content}">
<td class="test_code" th:text="${_r.testCode}"></td>
<td class="test_name" th:text="${_r.testName}"></td>
</tr>
</table>
<div th:insert="~{/page/pagination :: pagination}"></div>
</body>
</html>
pagination.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title></title>
</head>
<body th:fragment="pagination">
<ul id="pagination">
<li>
<span th:if="${page.isFirst}">≪</span>
<a th:if="${not page.isFirst}" th:href="@{/test_search(page=0, size=${page.size})}">≪</a>
</li>
<li>
<span th:if="${not page.hasPrevious}"><</span>
<a th:if="${page.hasPrevious}" th:href="@{/test_search(page=${page.number - 1}, size=${page.size})}"><</a>
</li>
<li>
<span th:if="${not page.hasNext}">></span>
<a th:if="${page.hasNext}" th:href="@{/test_search(page=${page.number + 1}, size=${page.size})}">></a>
</li>
<li>
<span th:if="${page.isLast}">≫</span>
<a th:if="${not page.isLast}" th:href="@{/test_search(page=${page.totalPages - 1}, size=${page.size})}">≫</a>
</li>
</body>
</html>
参考