Thymeleafでページング処理を実装

Thymeleafでページング処理を実装

Thymeleafでページング処理を実装するためには、サーバーサイドでページネーションの情報を管理し、Thymeleafテンプレートでそれを表示する必要があります。
以下は、ページング処理の基本的な実装例です。

サーバーサイド(Controller)

@Controller
public class PageController {

  @GetMapping("/items")
  public String getItems(Model model,
                         @RequestParam(defaultValue = "0") int page,
                         @RequestParam(defaultValue = "10") int size) {
    Pageable pageable = PageRequest.of(page, size);
    Page<Item> itemsPage = itemService.findAll(pageable);
    model.addAttribute("itemsPage", itemsPage);
    return "items";
  }
}

テンプレート(items.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>アイテムリスト</title>
</head>
<body>
  <h1>アイテムリスト</h1>
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>名前</th>
      </tr>
    </thead>
    <tbody>
      <tr th:each="item : ${itemsPage.content}">
        <td th:text="${item.id}"></td>
        <td th:text="${item.name}"></td>
      </tr>
    </tbody>
  </table>

  <div>
    <span>ページ:</span>
    <a th:if="${itemsPage.hasPrevious()}" th:href="@{/items(page=${itemsPage.number - 1}, size=${itemsPage.size})}">前へ</a>
    <span th:text="${itemsPage.number + 1}"></span>
    <a th:if="${itemsPage.hasNext()}" th:href="@{/items(page=${itemsPage.number + 1}, size=${itemsPage.size})}">次へ</a>
  </div>
</body>
</html>

説明

サーバーサイド(Controller)
PageControllerクラスで、/itemsのURLに対応するメソッドを定義しています。
ページ番号 (page) とサイズ (size) をクエリパラメータとして受け取り、Pageableを使ってデータを取得し、ModelにitemsPageを追加しています。

テンプレート(items.html)
itemsPageオブジェクトからアイテムのリストを取得し、テーブルに表示しています。
また、ページング用のリンクを表示し、前のページと次のページへのリンクを条件に応じて表示しています。

これで基本的なページング処理が実装できます。
実際の使用には、ItemクラスやitemServiceの実装が必要ですが、これがページング処理の一般的な流れです。