본문 바로가기
Spring/SpringBoot

[SpringBoot] 간단한 게시판 생성_페이징처리

by 코딩맛 2024. 1. 20.

1. 게시판 페이징 처리

1) controller

@GetMapping("/board/list")
public String boardList(Model model, @PageableDefault(page = 0, size = 10, sort = "id", direction = Sort.Direction.DESC) Pageable pageable, String searchKeyword){
    Page<Board> list = null;

    if(searchKeyword != null){
        list = boardService.boardSearchList(searchKeyword, pageable);
    } else {
        list = boardService.boardList(pageable);
    }

    int nowPage = list.getPageable().getPageNumber() + 1;
    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";
}

Pageable에 대한 설정

Model인자 : 데이터를 담아 페이지로 보내기 위해 사용

nowPage : 현재 페이지 가져옴, 0에서 시작하므로 +1

startPage : Math.max(a, b) -> a, b 중 큰 값 반환 , nowPage - 4는 5페이지씩 끊기 위함

endPage : Math.min(a, b) -> a, b 중 작은 값 반환, totalPage보다 크면 안 되므로 최소값 반환

 

2) service

public Page<Board> boardList(Pageable pageable){
    return boardRepository.findAll(pageable);
}

Board라는 class가 담긴 list를 찾아서 반환

매개변수가 없는 경우에는 public list

매개변수로 pageable을 주면 public pageable로 바뀜

 

Pageable 변수를 받을 수 있도록 설정, findAll에 pageable을 넘겨주도록 바꿈

 

기존 : public List 

pageble 변수 쓴 후 : public Page로 변경

 

3) view (html)

<th:bock th:each="page : ${#numbers.sequence(startPage, endPage)}">
    <a th:if="${page != nowPage}" th:href="@{/board/list(page = ${page-1}, searchKeyword = ${param.searchKeyword})}" th:text="${page}"></a>
    <strong th:if="${page == nowPage}" th:text="${page}" style="color : red"></strong>
</th:bock>

table 밑에 th:block을 만들어서 페이징 처리

현페이지와 누르려는 페이지가 같으면 href 작동 안 해도 되게끔 if문 사용

 

https://minddokddok.tistory.com/36?category=1040940

 

스프링 부트(Spring Boot)로 간단한 게시판 만들기 - 최종

7) 게시물 페이징 - 게시물 페이징 처리 를 해야할 차례이다. 페이징 처리란 무엇일까? 말 그대로 페이지화 시키는 것이다. 한 게시판에 만약 글이 만개 있다고 하면, 만 개의 글이 한 페이지에

minddokddok.tistory.com

위 해당글을 참고하였습니다.