1. 레포지토리 작성
2. 서비스 작성
3. 컨트롤러 작성
4. HTML 작성
5. 완성 화면
1. 레포지토리 작성
- JPA Paging 사용
- 댓글 레포지토리에 question과 pageable를 아규먼트로 넣어줌
파일 경로 : com.mysite.sbb/answer/AnswerRepository.java
public interface AnswerRepository extends JpaRepository<Answer, Integer> {
Page<Answer> findAllByQuestion(Question question, Pageable pageable);
}
2. 서비스 작성
- PageRequest 사용 방법 참고하여 작성
- 3개씩 끊어서 페이징
파일 경로 : com.mysite.sbb/answer/AnswerService.java
public Page<Answer> getList(Question question, int page) {
List<Sort.Order> sorts = new ArrayList<>();
sorts.add(Sort.Order.desc("createDate"));
Pageable pageable = PageRequest.of(page, 3, Sort.by(sorts));
return this.answerRepository.findAllByQuestion(question, pageable);
}
3. 컨트롤러 작성
- 아규먼트 부분에 페이지 변수 작성
- html에서 page 변수를 사용할 수 있게 model.addAttribute 메소드 작성
@RequestParam(value="page", defaultValue="0") int page
파일 경로 : com.mysite.sbb/question/QuestionController.java
@RequestMapping(value = "/detail/{id}")
public String detail(Model model, @PathVariable("id") Integer id, AnswerForm answerForm,
@RequestParam(value="page", defaultValue="0") int page) {
~ 생략 ~
Page<Answer> paging = this.answerService.getList(question, page);
model.addAttribute("paging", paging);
return "question_detail";
}
4. HTML 작성
- 게시글 페이징에서 했던 것과 같이 loop : ${paging} 으로 수정
- 페이징 버튼은 게시글 페이징의 소스와 똑같음
<div th:each="answer, loop : ${paging}">
파일 경로 : resources.templates/question_detail.html
<h5 class="border-bottom my-3 py-2"
th:text="|${#lists.size(question.answerList)}개의 댓글이 있습니다.|"></h5>
<div th:each="answer, loop : ${paging}">
~ 생략 ~
<!-- 페이징처리 시작 -->
<div th:if="${!paging.isEmpty()}">
<ul class="pagination justify-content-center">
<li class="page-item" th:classappend="${!paging.hasPrevious} ? 'disabled'">
<a class="page-link"
th:href="@{|?page=${paging.number-1}|}">
<span>이전</span>
</a>
</li>
<li th:each="page: ${#numbers.sequence(0, paging.totalPages-1)}"
th:if="${page >= paging.number-5 and page <= paging.number+5}"
th:classappend="${page == paging.number} ? 'active'"
class="page-item">
<a th:text="${page}" class="page-link" th:href="@{|?page=${page}|}"></a>
</li>
<li class="page-item" th:classappend="${!paging.hasNext} ? 'disabled'">
<a class="page-link" th:href="@{|?page=${paging.number+1}|}">
<span>다음</span>
</a>
</li>
</ul>
</div>
<!-- 페이징처리 끝 -->
5. 완성 화면
참고 페이지: [점프 투 스프링부트] 답변에 페이징이 쉽지가 않습니다.
'Language > Springboot' 카테고리의 다른 글
[Stringboot] 네이버지도 API에 현재 위치 받아오기 (0) | 2022.08.28 |
---|---|
[Stringboot] 제이쿼리(jQuery) 적용하기 (0) | 2022.08.28 |
[Springboot] 웹에 네이버지도 API 추가하기 (0) | 2022.08.26 |
[Springboot] 게시글 조회수 구현하기 (1) | 2022.08.25 |
[Springboot] 게시글 이전글 다음글 쿼리(Oracle) 및 구현하기 (+8/27 수정) (0) | 2022.08.25 |