인생 디벨로퍼

myBatis 페이징 연습 본문

JAVA Spring

myBatis 페이징 연습

뫄뫙뫄 2023. 6. 20. 12:57
728x90
반응형

util

package shop.mtcoding.newblog.util;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class PagingVO {
    private int nowPage, startPage, endPage, cntPerPage, total, lastPage, start, end;
    private int cntPage = 5;

    //nowPage(현재페이지), startPage(시작페이지), endPage(끝페이지), cntPerPage(페이지당 글 수), 
    //total(글 총 수), lastPage(마지막페이지), start, end => 쿼리에 쓸 변수

    public PagingVO() {
    }

    public PagingVO(int total, int nowPage, int cntPerPage) {
        setNowPage(nowPage);
        setCntPerPage(cntPerPage);
        setTotal(total);
        calcLastPage(getTotal(), getCntPerPage());
        calcStartEndPage(getNowPage(), cntPage);
        calcStartEnd(getNowPage(), getCntPerPage());
    }

    // 제일 마지막 페이지 계산O
    public void calcLastPage(int total, int cntPerPage) {
        setLastPage((int) Math.ceil((double) total / (int) cntPerPage));
        // ceil 소수점 앞으로 올림. (int 캐스팅)
    }

    // 시작, 끝 페이지 계산
    public void calcStartEndPage(int nowPage, int cntPage) {
        setEndPage(((int) Math.ceil((double) nowPage / (double) cntPage)) * cntPage);
        if (getLastPage() < getEndPage()) {
            setEndPage(getLastPage());
            //마지막 페이지 < 현재 뷰의 끝페이지 =>현재 뷰의 끝 페이지가 마지막 페이지
        }
        setStartPage(getEndPage() - cntPage + 1);
        if (getStartPage() < 1) {
            setStartPage(1);
            //시작페이지가 1 보다 작으면, 시작페이지는 1 페이지
        }
    }

    // DB 쿼리에서 사용할 start, end값 계산
    public void calcStartEnd(int nowPage, int cntPerPage) {
        setEnd(nowPage * cntPerPage);
        setStart(getEnd() - cntPerPage + 1);
        //현재페이지 * 게시글 수(8개) = 현재페이지 마지막 게시글 id
    }

    @Override
    public String toString() {
        return "PagingVO [nowPage=" + nowPage + ", startPage=" + startPage + ",endPage=" + endPage + ", total=" + total
                + ", cntPerPage=" + cntPerPage + ", lastPage=" + lastPage + ", start=" +
                start + ", end=" + end
                + ", cntPage=" + cntPage + "]";
    }

}

 


Controller

   @GetMapping({ "/", "board" })
    public String main(Model model, BoardListRespDto boardListRespDto,
            @RequestParam(defaultValue = "1", value = "nowPage", required = false) String nowPage,
            @RequestParam(value = "cntPerPage", required = false) String cntPerPage) {

        model.addAttribute("dtos", boardRepository.findAllWithUser());

        int total = boardRepository.countBoard();
        if (nowPage == null && cntPerPage == null) {
            nowPage = "1";
            cntPerPage = "8";
        } else if (nowPage == null) {
            nowPage = "1";
        } else if (cntPerPage == null) {
            cntPerPage = "8";
        }
        PagingVO vo = new PagingVO(total, Integer.parseInt(nowPage), Integer.parseInt(cntPerPage));
        // Integer.parseInt(nowPage) 문자열 정수 변환
        model.addAttribute("paging", vo);

        List<BoardListRespDto> boardList = boardRepository.findAllWithPaging(vo);
        model.addAttribute("boardList", boardList);

        return "board/main";
    }


Repository

  // 게시물 총 갯수
        public int countBoard();

        // 페이징 처리 게시글 조회
        public List<BoardListRespDto> findAllWithPaging(PagingVO vo);

.xml

    <select id="findAllWithPaging" resultType="shop.mtcoding.newblog.dto.board.BoardResp$BoardListRespDto">
         SELECT * FROM (
            SELECT ROWNUM RN, A.* FROM (
                select bt.id, bt.title, bt.content, bt.thumbnail, bt.user_id, ut.username
                        from board_tb bt
                        inner join user_tb ut
                        on bt.user_id = ut.id
                ORDER BY id DESC ) A) 
        WHERE RN BETWEEN #{start} AND #{end}
    </select>

    <select id="countBoard" resultType="int">
        SELECT COUNT(*) FROM BOARD_TB
    </select>

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    <%@ include file="../layout/header.jsp" %>

        <div class="container my-3">
            <div class="my-board-box row">
                <c:forEach items="${boardList}" var="boardList">
                    <div class="card col-lg-3 pt-2" >
                        <img class="card-img-top" style="height: 250px;" src="${boardList.thumbnail}" alt="Card image">
                        <div class="card-body">
                            <div>작성자 : ${boardList.username}</div>
                            <h4 class="card-title my-text-ellipsis">${boardList.title}</h4>
                            <a href="/board/${boardList.id}" class="btn btn-primary">상세보기</a>
                        </div>
                    </div>
                </c:forEach>

            </div>
      
        </div>

    
        <nav aria-label="Page navigation example">
            <ul class="pagination justify-content-center">
            
                <c:if test="${paging.startPage != 1 }">
                    <li class="page-item">
                        <a class="page-link" href="/board?nowPage=${paging.startPage - 1 }&cntPerPage=${paging.cntPerPage}">Previous</a>
                    </li>
                </c:if>

                
		        <c:forEach begin="${paging.startPage }" end="${paging.endPage }" var="p">
                    <c:choose>
                        <c:when test="${p == paging.nowPage }">
					        <li class="page-item"><b class="page-link">${p }</b></li>
				        </c:when>
                        <c:when test="${p != paging.nowPage }">
                            <li class="page-item"><a class="page-link" href="/board?nowPage=${p }&cntPerPage=${paging.cntPerPage}">${p }</a></li>
                        </c:when>
                    </c:choose>
                </c:forEach>

                <c:if test="${paging.endPage != paging.lastPage}">
                    <li class="page-item">
                        <a class="page-link" href="/board?nowPage=${paging.endPage+1 }&cntPerPage=${paging.cntPerPage}">Next</a>
                    </li>
                </c:if>
        </ul>
        </nav>

        <%@ include file="../layout/footer.jsp" %>

 

728x90
반응형

'JAVA Spring' 카테고리의 다른 글

Spring security + my batis  (0) 2024.03.11
myBatis 검색 연습, 검색 쿼리 (.feat 페이징)  (0) 2023.06.23
Cookie 아이디 저장하기  (0) 2023.06.18
[Ajax] 비밀번호 확인  (0) 2023.06.18
[Ajax] 좋아요 만들기!  (0) 2023.06.18