What to do?
Pagination
게시판 페이지에서 페이징 바 구현하기
구현 내용
- 1페이지를 보여줄 때는 Previous버튼과 1페이지 버튼은 disabled 됨
- 페이지가 변하면, 가운데 현재 페이지를 보여주도록 함
Service
- Param
- currentPage - 현재페이지번호
- totalPage - 전체페이지수
- Return
- 페이지 List
ArticleService에 getPaginationBarNumbers 메써드 추가
public List<Integer> getPaginationBarNumbers(int currentPage, int totalPage){
int startPage = Math.max(0, currentPage-(PAGINATION_BAR_LENGTH/2));
int endPage = Math.min(totalPage, startPage+PAGINATION_BAR_LENGTH);
return IntStream.range(startPage, endPage).boxed().collect(Collectors.toList());
}
Controller
- Service코드에서 만든 getPaginationBarNumbers 메써드 사용
- currentPage → pageable.getPageNumber()
- totalPage → articleDtoPage.getTotalPages()
- model에 pagination이라는 이름으로 pagination 전달
public String articles(
@RequestParam(required = false) SearchType searchType,
@RequestParam(required = false) String keyword,
@PageableDefault(size=20, sort = "createdAt", direction = Sort.Direction.DESC)Pageable pageable,
ModelMap map){
Page<ArticleDto> articleDtoPage = articleService.searchArticleDtoPage(searchType, keyword, pageable);
List<Integer> pagination = articleService.getPaginationBarNumbers(pageable.getPageNumber(), articleDtoPage.getTotalPages());
map.addAttribute("articles", articleDtoPage.map(ArticlesResponse::from));
map.addAttribute("pagination", pagination);
return "article/index";
}
Template
resources/article/index.html
<!--Pagination-->
<div class="d-flex justify-content-center mt-5">
<nav id="pagination" name="pagination">
<ul class="pagination">
<li class="page-item"><a class="page-link" href="#">Previous</a></li>
<li class="page-item"><a class="page-link"/></li>
<li class="page-item"><a class="page-link" href="#">Next</a></li>
</ul>
</nav>
</div>
resources/article/index.th.xml
- 현재 페이지 번호 → articles.number
- 전체 페이지수 → articles.totalPages
- article.number <= 0 → previous 버튼을 못누르게 해야함 → class명에 disabled를 넣음
- article.number >= articles.totalPages → previous 버튼을 못누르게 해야함 → class명에 disabled를 넣음
<!--Pagination-->
<attr sel="#pagination">
<!--Previous 버튼-->
<attr sel="li[0]/a"
th:text="'previous'"
th:href="@{/articles(page=${articles.number - 1})}"
th:class="'page-link' + (${articles.number} <= 0 ? ' disabled' : '')"
/>
<!--페이지 번호 버튼-->
<attr sel="li[1]" th:class="page-item" th:each="page : ${pagination}">
<attr sel="a"
th:text="${page + 1}"
th:href="@{/articles(page=${page})}"
th:class="'page-link' + (${page} == ${articles.number} ? ' disabled' : '')"
/>
</attr>
<!--Next 버튼-->
<attr sel="li[2]/a"
th:text="'next'"
th:href="@{/articles(page=${articles.number + 1})}"
th:class="'page-link' + (${articles.number} >= ${articles.totalPages - 1} ? ' disabled' : '')"
/>
</attr>
'Java > Spring' 카테고리의 다른 글
[Spring] 게시판 만들기 #10 (0) | 2022.11.23 |
---|---|
[Spring] 게시판 만들기 #9 (0) | 2022.11.23 |
[Spring] 게시판 만들기 #7 (0) | 2022.11.22 |
[Spring] 게시판 만들기 #6 (0) | 2022.11.21 |
[Spring] 게시판 만들기 #5 (0) | 2022.11.14 |