💻 my code archive/🎨게시판 만들기
[스프링부트 게시판 만들기] pageable 사용하여 간단한 페이징 처리 구현하기
얼레벌레 개발자👩💻
2022. 3. 13. 17:32
반응형
스프링 레거시 프로젝트를 할 땐 페이징 관련 vo를 따로 만들고 다소 복잡한 방식으로 페이징 처리를 했었는데 스프링부트에서는 JPA의 Pageable 인터페이스를 사용해서 훨씬 간단한 페이징 처리 구현이 가능하다.
🤍간단한 페이징 처리 구현하기
1. 컨트롤러 API에서 Pageable 인터페이스 타입으로 파라미터를 받는다.
- 인터페이스는 getPageNumber(), getPageSize() 등등 페이징 구현 시 필요한 값을 편하게 구할 수 있는 메소드를 갖고 있다.
위 코드를 설명하면
- page : default 페이지
- size : 한 페이지 게시글 수
- sort : 정렬 기준 컬럼(여기에서는 글 번호 id)
- direction : 정렬 순서 (보통 게시판은 최근 글이 위로 올라와 있기 때문에 역순으로 설정함.)
그리고 페이징 처리를 위해 변수 3개를 선언해 준다.
- nowPage : 현재 페이지
- startPage : 블럭에서 보여줄 시작 페이지
- endPage : 블럭에서 보여줄 마지막 페이지
JPA의 Pageable에서는 페이지가 0부터 시작한다. 우리가 생각하는 1페이지가 여기에서는 0페이지이다. 그래서 nowPage는 +1을 더해주고, startPage는 음수가 되지 않도록, endPage는 총 게시글 수를 넘지 않도록 아래와 같이 Math.max, Math.min을 사용해 준다.
컨트롤러 API 전체 코드
@GetMapping("/board/list") /*page:default 페이지,size:한 페이지 게시글 수, sort:정렬기준컬럼, direction:정렬순서 */
public String boardList(Model model,@PageableDefault(page = 0,size = 10,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
Page<Bootboard> list = boardService.boardList(pageable);
int nowPage = list.getPageable().getPageNumber()+1; //pageable이 갖고 있는 페이지는 0부터 시작하기 때문에
int startPage = Math.max(nowPage -4,1);
int endPage = Math.min(nowPage +5,list.getTotalPages());
model.addAttribute("list",list);
model.addAttribute("nowPage",nowPage);
model.addAttribute("startPage",startPage);
model.addAttribute("endPage",endPage);
return "boardList";
}
이제 화면에 페이지 숫자가 잘 출력되도록 boardList.html을 수정해 준다.
<!--굳이 태그로 감쌀 필요 없는 부분을 타임리프 문법으로 사용할 때 사용-->
<th:block th:each="page:${#numbers.sequence(startPage, endPage)}">
<a th:if="${page != nowPage}" th:href="@{/board/list(page=${page -1})}" th:text="${page}"></a>
<strong th:if="${page == nowPage}" th:text="${page}" style="color:red"></strong>
</th:block>
실행 전 기존 게시물 목록 페이지를 보면 최신 글이 맨 아래에 내려가 있고 페이징 처리도 되지 않았다.
실행 후 비교해보면 이렇게 페이징 처리가 간단하게 완성되었다!!
반응형