リストのThymeleafページネーションを使用した春
1. 概要
このクイックチュートリアルでは、SpringとThymeleafを使用してページ付けされたアイテムのリストを表示する簡単なアプリケーションを作成します。
ThymeleafをSpringと統合する方法の概要については、こちらの記事をご覧ください。
2. Mavenの依存関係
通常のSpring依存関係に加えて、ThymeleafおよびSpring Dataコモンズの依存関係を追加します。
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
最新のthymeleaf-spring5およびspring-data-commonsの依存関係はMavenCentralリポジトリにあります。
3. モデル
サンプルアプリケーションは、本のリストのページネーションを示します。
まず、2つのフィールドとすべての引数のコンストラクターを使用してBookクラスを定義しましょう。
public class Book {
private int id;
private String name;
// standard constructor, setters and getters
}
4. サービス
次に、Spring Data Commonsライブラリを使用して、要求されたページのページ付けされた書籍リストを生成するサービスを作成します。
@Service
public class BookService {
final private List<Book> books = BookUtils.buildBooks();
public Page<Book> findPaginated(Pageable pageable) {
int pageSize = pageable.getPageSize();
int currentPage = pageable.getPageNumber();
int startItem = currentPage * pageSize;
List<Book> list;
if (books.size() < startItem) {
list = Collections.emptyList();
} else {
int toIndex = Math.min(startItem + pageSize, books.size());
list = books.subList(startItem, toIndex);
}
Page<Book> bookPage
= new PageImpl<Book>(list, PageRequest.of(currentPage, pageSize), books.size());
return bookPage;
}
}
上記のサービスでは、 Pageable インターフェイスで表される、要求されたページに基づいて選択されたページを返すメソッドを作成しました。 PageImpl クラスは、ページ化された本のリストを除外するのに役立ちます。
5. スプリングコントローラー
ページサイズと現在のページ番号が指定されたときに、選択したページのブックリストを取得するには、Springコントローラーが必要です。
選択したページとページサイズのデフォルト値を使用するには、パラメータなしで /listBooksのリソースにアクセスするだけです。
ページサイズまたは特定のページが必要な場合は、パラメータpageおよびsizeを追加できます。
例えば、 / listBooks?page = 2&size = 6 1ページに6つのアイテムがある2ページ目を取得します。
@Controller
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping(value = "/listBooks", method = RequestMethod.GET)
public String listBooks(
Model model,
@RequestParam("page") Optional<Integer> page,
@RequestParam("size") Optional<Integer> size) {
int currentPage = page.orElse(1);
int pageSize = size.orElse(5);
Page<Book> bookPage = bookService.findPaginated(PageRequest.of(currentPage - 1, pageSize));
model.addAttribute("bookPage", bookPage);
int totalPages = bookPage.getTotalPages();
if (totalPages > 0) {
List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.collect(Collectors.toList());
model.addAttribute("pageNumbers", pageNumbers);
}
return "listBooks.html";
}
}
ビューのページネーションを準備するために、Springコントローラーに、選択したページとページ番号のリストを含むモデル属性を追加しました。
6. Thymeleafテンプレート
次に、Thymeleafテンプレート「listBooks.html」を作成します。このテンプレートは、Springコントローラーのモデル属性に基づいてページ付けされた書籍のリストを表示します。
まず、本のリストを繰り返して、テーブルに表示します。 次に、ページの総数がゼロより大きい場合のページネーションを表示します。
ページをクリックして選択するたびに、対応する書籍のリストが表示され、現在のページのリンクが強調表示されます。
<table border="1">
<thead>
<tr>
<th th:text="#{msg.id}" />
<th th:text="#{msg.name}" />
</tr>
</thead>
<tbody>
<tr th:each="book, iStat : ${bookPage.content}"
th:style="${iStat.odd}? 'font-weight: bold;'"
th:alt-title="${iStat.even}? 'even' : 'odd'">
<td th:text="${book.id}" />
<td th:text="${book.name}" />
</tr>
</tbody>
</table>
<div th:if="${bookPage.totalPages > 0}" class="pagination"
th:each="pageNumber : ${pageNumbers}">
<a th:href="@{/listBooks(size=${bookPage.size}, page=${pageNumber})}"
th:text=${pageNumber}
th:class="${pageNumber==bookPage.number + 1} ? active"></a>
</div>
7. 結論
この記事では、SpringフレームワークでThymeleafを使用してリストをページ分割する方法を示しました。
いつものように、この記事で使用されているすべてのコードサンプルは、GitHubでから入手できます。