스프링/게시판 프로젝트

스프링부트 페이징처리 구현 연습

까마귀! 2024. 4. 5. 16:13

 

data.sql로 대량의 데이터를 만든다음 목록을 만든다.

 

ArticleController.java
//목록
@GetMapping("/articles")
public String index(Model model, @PageableDefault(page = 0, size = 5, sort = "id", direction = Sort.Direction.DESC)Pageable pageable,
                    String searchKeyword){

    Page<article> list = null;
    list = articleService.articleList(pageable);


    int nowPage = list.getPageable().getPageNumber()+1; // or Pageable.getPageNumber() 현재페이지
    int totalPage = list.getTotalPages(); // 총 페이지
    int pageSize = 10; // 한 페이지에 보여질 페이지 수
    int pageGroupSize = 10; // 한 페이지 그룹에 포함될 페이지 수

    int startPage = ((nowPage-1) / pageSize) * pageSize + 1;
    int endPage = Math.min(startPage + pageGroupSize - 1, totalPage);

    model.addAttribute("article",list);
    model.addAttribute("nowPage", nowPage);
    model.addAttribute("startPage", startPage);
    model.addAttribute("endPage", endPage);
    model.addAttribute("txt","변하지 않는 문장");

    return "article/index3";
}

 

 

 

ArticleService.java
@Service
public class ArticleService {

    @Autowired
    private articleRepository articleRepository;

    // 게시글 리스트 처리
    public Page<article> articleList(Pageable pageable) {
        return articleRepository.findAll(pageable);
    }

}

 

 

 

 

index3.html
<!-- 검색 -->
<form th:action="@{/articles}" method="get">
    <input type="text" name="searchKeyword">
    <button type="submit">검색</button>
</form>

<table>
    <span><a th:href="@{/new}">생성</a></span>
    <thead>
    <tr>
        <th scope="col">번호</th>
        <th scope="col">제목</th>
        <th scope="col">조회수</th>
        <th scope="col">삭제</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="a : ${article}">
        <th th:text="${a.id}"></th>
        <td><a th:href="@{/article/{id}/detail(id=${a.id})}" th:text="${a.title}"></a></td>
        <td th:text="${a.getView}"></td>
        <td><a th:href="@{/article/{id}/delete(id=${a.id})}">삭제</a></td>
    </tr>
    </tbody>

</table>

<!-- 이전 링크 활성화 비활성화 -->
<a th:if="${!article.first}" th:href="@{/articles(page = ${nowPage -2})}"> 이전 </a>
<a th:if="${article.first}" th:href="@{#}"> 이전 </a>

<!-- 페이지 처리 -->
<th:block th:each="page : ${#numbers.sequence(startPage, endPage)}">
    <a th:if="${page != nowPage}" th:href="@{/articles(page =  ${page - 1})}" th:text="${page}"></a>
    <strong th:if="${page == nowPage}" th:text="${page}" style="color: red"></strong>
</th:block>

<!-- 다음 링크 활성화 비활성화 -->
<a th:if="${!article.last}" th:href="@{/articles(page = ${nowPage})}">다음 </a>
<a th:if="${article.last}" th:href="@{#}"> 다음 </a>

 

 

url에서 페이지가 0이면 page는 1로 표시된다는걸 알았다.  이걸 고려해서 계산해야 한다

'스프링 > 게시판 프로젝트' 카테고리의 다른 글

스프링부트 복합키 연습  (0) 2024.04.05
파일 생성 연습  (2) 2024.03.23