본문 바로가기

서버/SprintBoot
[스프링부트(Spring Boot)] 페이징(Paging)

// 페이징

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;


- Controller에서 Pagable 설정하기

@GetMapping("/board/list")
public String boardList(Model model, @PageableDefault(page = 0, size = 10, sort = "id", direction = Sort.Direction.DESC) Pageable pagable) {

    Page<Board> list = boardService.boardList(pagable);

    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";
}


- Service에서 pagable 넘겨주기

public Page<Board> boardList(Pageable pagable) {

	return boardRepository.findAll(pagable);
}


- 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>

* 기능 중심으로 공부하느라 css는 아예 안 만졌다 ㅎ
    + 페이지 버튼 수도 조절하려면 더 꼼꼼히 작업해야 한다.