[TIL] 프론트 단 페이징처리 paging

hyewon jeong·2023년 2월 16일
0

TIL

목록 보기
93/138

개발 진행에 따른 기록 작성(★★★★★)

1. 엔티티 재 설계

1. 어떠한 이유로 해당 기능을 사용하였는지

프론트단에서 총페이지수, 현재페이지 번호, 시작번호, 끝번호를 알아야 구현 할 수 있어
기존 페이지처리 코드를 리팩토링 했다.

2. 해당 기능의 코드는 어떠한 로직을 가지고 있는지

📌NoticeService class

  @Transactional(readOnly = true)
  @Override
  public Result getNoticeList(int page, int size, Direction direction,
      String properties) {

    Page<Notice> noticeListPage = noticeRepository.findAll(
        PageRequest.of(page - 1, size, direction, properties));
    int totalCount = (int) noticeListPage.getTotalElements(); //페이지에서 총갯수 세기
    System.out.println("totalCount:"+totalCount);

    if (noticeListPage.isEmpty()) {
      throw new CustomException(ExceptionStatus.POST_IS_EMPTY);
    }
    List<NoticeResponse> noticeResponses = noticeListPage.stream().map(NoticeResponse::new).collect(
        Collectors.toList());
    int countList = size;
    int countPage = 5;//todo 리팩토링때  10으로 변경예정
    int totalPage = totalCount / countList;
    if (totalCount % countList > 0) {
      totalPage++;
    }
    if (totalPage < page) {
      page = totalPage;
    }
    return new Result(page, totalCount, countPage, totalPage, noticeResponses);
  }


    @Getter
  @NoArgsConstructor(access = AccessLevel.PROTECTED)
  public static class Result<T> {

    private int page;
    private int totalCount;
    private int countPage;
    private int totalPage;
    private T data;

    public Result(int totalCount, T data) {
      this.totalCount = totalCount;
      this.data = data;
    }

    public Result(int page, int totalCount, int countPage, int totalPage, T data) {
      this.page = page;
      this.totalCount = totalCount;
      this.countPage = countPage;
      this.totalPage = totalPage;
      this.data = data;
    }
  }
  

vs-code이용📌contactPageIndex-inquiry.html

                      <!-- 검색기능 -->
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" placeholder="제목 및 내용 " aria-label="Recipient's username"
                            aria-describedby="button-addon2" id="keyword-in-Input">
                        <button class="btn btn-outline-secondary" type="button" onclick="noticeSearch()">검색</button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-12">
                        <div class="property-slider-wrap">
                            <div class="property-slider"></div>

                            <!-- 게시글 목록 -->
                            <div class="container">
                                <button type="button" class="btn btn-outline-secondary border">
                                    <a href="contactWrite.html">글쓰기</a>
                                </button>
                                <table class="table table-hover table-striped " style="border:1px solid;">
                                    <thead>
                                        <tr>
                                            <th>번호</th>
                                            <th>제목</th>
                                            <th>작성일</th>
                                            <!-- <th>조회수</th> -->
                                        </tr>
                                    </thead>
                                    <tbody id="inquiryList"></tbody>

                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- .페이지번호 -->
                    <div class="row align-items-center py-5">
                        <div class="col-lg-3">Pagination (1 of 10)</div>
                        <div class="col-lg-6 text-center">
                            <div class="custom-pagination" id="inquiryPaging">
                                <!-- 페이지번호 temp_html -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <script>
                $(document).ready(function () {
                    showInquiry();
                });
                // 전체조회
                function showInquiry() {
                    var settings = {
                        "url": "http://localhost:8080/api/contact/inquiries",

                        "method": "GET",
                        "timeout": 0
                    };

                    $
                        .ajax(settings)
                        .done(function (response) {
                            console.log(response);
                            let rows = response.data
                            for (let i = 0; i < rows.length; i++) {
                                let inquiryId = rows[i]['id']
                                let number = inquiryId
                                let title = rows[i]['title']
                                let createdDate = rows[i]['createdDate']

                                let temp_html = ` <tr>
                                   <td>${number}</td>
                                   <td><a href ="contactDe-inquiry.html?${inquiryId}">${title}</td>
                                   <th>${createdDate}</th> 
                                 </tr>`

                                $('#inquiryList').append(temp_html)
                            }
                            let page = response.page
                            let totalCount = response.totalCount
                            let countPage = response.countPage
                            let startPage = ((page - 1) / 10) * 10 + 1;
                            let endPage = startPage + countPage - 1;
                            let totalPage = response.totalPage;
                            if (totalPage < page) {
                                page = totalPage;
                            }
                            if (endPage > totalPage) {
                                endPage = totalPage
                            }

                            for (let i = startPage; i <= endPage; i++) {
                                let number = i
                                let temp_html = `<a href="contactPageMove-inquiry.html?${number}">${number}</a>`

                                $('#inquiryPaging').append(temp_html);
                            }
                        }).fail(function (response) {
                            console.log(response.responseJSON);
                            if (response.responseJSON.statusCode === 403) {
                                alert(response.responseJSON.message)
                            }
                        });

                }

                // 검색창조회
                function inquirySearch() {
                    var settings = {
                        "url": "http://localhost:8080/api/contact/inquiries/keywords?keyword=" + $(
                            '#keyword-in-Input'
                        ).val(),
                        "method": "GET",
                        "timeout": 0
                    };

                    $
                        .ajax(settings)
                        .done(function (response) {
                            $('#inquiryList').empty()
                            console.log(response);
                            let rows = response.data;
                            for (let i = 0; i < rows.length; i++) {
                                let number = rows[i][id]
                                let title = rows[i]['title']
                                let createdDate = rows[i]['createdDate']

                                let temp_html = ` <tr>
                                   <td>${number}</td>
                                   <td>${question}</td>
                                   <th>${createdDate}</th> 
                                 </tr>`

                                $('#inquiryList').append(temp_html)
                            }
                            alert("조회 성공");
                        }).fail(function (response) {
                            console.log(response.responseJSON);
                            if (response.responseJSON.statusCode === 403) {
                                alert(response.responseJSON.message)
                            }
                        });
                }
            </script>
            <div class="site-footer">
                <div class="container">
                    <div class="row">
                        <div class="col-lg-4">
                            <div class="widget">
                                <h3>Contact</h3>
                                <address>43 Raymouth Rd. Baltemoer, London 3910</address>
                                <ul class="list-unstyled links">
                                    <li>
                                        <a href="tel://11234567890">+1(123)-456-7890</a>
                                    </li>
                                    <li>
                                        <a href="tel://11234567890">+1(123)-456-7890</a>
                                    </li>
                                    <li>
                                        <a href="mailto:info@mydomain.com">info@mydomain.com</a>
                                    </li>
                                </ul>
                            </div>
                            <!-- /.widget -->
                        </div>
                        <!-- /.col-lg-4 -->
                        <div class="col-lg-4">
                            <div class="widget">
                                <h3>Sources</h3>
                                <ul class="list-unstyled float-start links">
                                    <li>
                                        <a href="#">About us</a>
                                    </li>
                                    <li>
                                        <a href="#">Services</a>
                                    </li>
                                    <li>
                                        <a href="#">Vision</a>
                                    </li>
                                    <li>
                                        <a href="#">Mission</a>
                                    </li>
                                    <li>
                                        <a href="#">Terms</a>
                                    </li>
                                    <li>
                                        <a href="#">Privacy</a>
                                    </li>
                                </ul>
                                <ul class="list-unstyled float-start links">
                                    <li>
                                        <a href="#">Partners</a>
                                    </li>
                                    <li>
                                        <a href="#">Business</a>
                                    </li>
                                    <li>
                                        <a href="#">Careers</a>
                                    </li>
                                    <li>
                                        <a href="#">Blog</a>
                                    </li>
                                    <li>
                                        <a href="#">FAQ</a>
                                    </li>
                                    <li>
                                        <a href="#">Creative</a>
                                    </li>
                                </ul>
                            </div>
                            <!-- /.widget -->
                        </div>
                        <!-- /.col-lg-4 -->
                        <div class="col-lg-4">
                            <div class="widget">
                                <h3>Links</h3>
                                <ul class="list-unstyled links">
                                    <li>
                                        <a href="#">Our Vision</a>
                                    </li>
                                    <li>
                                        <a href="#">About us</a>
                                    </li>
                                    <li>
                                        <a href="#">Contact us</a>
                                    </li>
                                </ul>

                                <ul class="list-unstyled social">
                                    <li>
                                        <a href="#">
                                            <span class="icon-instagram"></span></a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <span class="icon-twitter"></span></a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <span class="icon-facebook"></span></a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <span class="icon-linkedin"></span></a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <span class="icon-pinterest"></span></a>
                                    </li>
                                    <li>
                                        <a href="#">
                                            <span class="icon-dribbble"></span></a>
                                    </li>
                                </ul>
                            </div>
                            <!-- /.widget -->
                        </div>
                        <!-- /.col-lg-4 -->
                    </div>
                    <!-- /.row -->

                    <div class="row mt-5">
                        <div class="col-12 text-center">
                            <!-- **========== NOTE: Please don't remove this copyright link unless you buy
                                the license here https://untree.co/license/ **========== -->

                            <p>
                                Copyright &copy;
                                <script>
                                    document.write(new Date().getFullYear());
                                </script>
                                . All Rights Reserved. &mdash; Designed with love by
                                <a href="https://untree.co">Untree.co</a>
                                <!-- License information: https://untree.co/license/ -->
                            </p>
                            <div>
                                Distributed by
                                <a href="https://themewagon.com/" target="_blank">themewagon</a>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /.container -->
            </div>
            <!-- /.site-footer -->

            <!-- Preloader -->
            <div id="overlayer"></div>
            <div class="loader">
                <div class="spinner-border" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </div>

            <script src="js/bootstrap.bundle.min.js"></script>
            <script src="js/tiny-slider.js"></script>
            <script src="js/aos.js"></script>
            <script src="js/navbar.js"></script>
            <script src="js/counter.js"></script>
            <script src="js/custom.js"></script>

</body>

</html>

vs-code이용 📌contactPageMove-inquiry.html

  
                        <!-- 검색기능 -->
                        <div class="input-group mb-3">
                            <input
                                type="text"
                                class="form-control"
                                placeholder="제목 및 내용 "
                                aria-label="Recipient's username"
                                aria-describedby="button-addon2"
                                id="keyword-in-Input">
                            <button
                                class="btn btn-outline-secondary"
                                type="button"
                                onclick="inquirySearch()">검색</button>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12">
                            <div class="property-slider-wrap">
                                <div class="property-slider"></div>

                                <!-- 게시글 목록 -->
                                <div class="container">
                                    <button type="button" class="btn btn-outline-secondary border">
                                        <a href="contactWrite.html">글쓰기</a>
                                    </button>
                                    <table class="table table-hover table-striped " style="border:1px solid;">
                                        <thead>
                                            <tr>
                                                <th>번호</th>
                                                <th>제목</th>
                                                <th>작성일</th>
                                                <!-- <th>조회수</th> -->
                                            </tr>
                                        </thead>
                                        <tbody id="inquiryList"></tbody>

                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- .페이지번호 -->
                        <div class="row align-items-center py-5">
                            <div class="col-lg-3">Pagination (1 of 10)</div>
                            <div class="col-lg-6 text-center">                              
                                <div class="custom-pagination" id="inquiryPaging">
                                    <!-- 페이지번호 temp_html -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <script>
                    $(document).ready(function () {
                        showInquiry();
                    });
                    // 전체조회
                    function showInquiry() {
                        var para = document
                            .location
                            .href
                            .split("?");
                        console.log(para[1])
                        var settings = {
                            "url": "http://localhost:8080/api/contact/inquiries?page=" + para[1],

                            "method": "GET",
                            "timeout": 0
                        };

        
                        $
                            .ajax(settings)
                            .done(function (response) {
                                console.log(response);
                                let rows = response.data
                                for (let i = 0; i < rows.length; i++) {
                                    let inquiryId = rows[i]['id']
                                    let number = inquiryId
                                    let title = rows[i]['title']
                                    let createdDate = rows[i]['createdDate']
        
                                    let temp_html = ` <tr>
                                   <td>${number}</td>
                                   <td><a href ="contactDe-inquiry.html?${inquiryId}">${title}</td>
                                   <th>${createdDate}</th> 
                                 </tr>`
        
                                    $('#inquiryList').append(temp_html)
                                }
                                let page = response.page
                                let totalCount = response.totalCount
                                let countPage = response.countPage
                                let startPage = ((page - 1) / 10) * 10 + 1;
                                let endPage = startPage + countPage - 1;
                                let totalPage = response.totalPage;
                                if(totalPage < page){
                                        page = totalPage;
                                       }
                                       if(endPage>totalPage){
                                        endPage = totalPage
                                       }


                                var param = document
                                    .location
                                    .href
                                    .split("=");
                                console.log(param[1])
                                //이전페이지
                                if (page > 1) {
                                    let temp_html = `<a href="contactPageMove-inquiry.html?${page - 1}">pre</a>`
                                    $('#inquiryPaging').append(temp_html);
                                }
                                //한 화면에 보여지는 페이지 수만큼 반복 하여 번호로 나타냄
                                for (let i = startPage; i<=endPage; i++) {
                                    let number = i
                                    let temp_html = `<a href="contactPageMove-inquiry.html?${number}">${number}</a>`
                                    $('#inquiryPaging').append(temp_html);
                                }
                                //다음페이지 page
                                if (page < totalPage) {
                                    let temp_html = `<a href="contactPageMove-inquiry.html?${page + 1}">next</a>`

                                    $('#inquiryPaging').append(temp_html);
                                }

                            })                            .fail(function (response) {
                                console.log(response.responseJSON);
                                if (response.responseJSON.statusCode === 403) {
                                    alert(response.responseJSON.message)
                                }
                            });
                    }
        
                    // 검색창조회
                    function inquirySearch() {
                        var settings = {
                            "url": "http://localhost:8080/api/contact/inquiries/keywords?keyword="+ $(
                                '#keyword-in-Input'
                            ).val(),
                            "method": "GET",
                            "timeout": 0
                        };
        
                        $
                            .ajax(settings)
                            .done(function (response) {
                                $('#inquiryList').empty()
                                console.log(response);
                                let rows = response.data;
                                for (let i = 0; i < rows.length; i++) {
                                    let number = rows[i]['id']
                                    let title = rows[i]['title']
                                    let createdDate = rows[i]['createdDate']
        
                                    let temp_html = ` <tr>
                                   <td>${number}</td>
                                   <td>${title}</td>
                                   <th>${createdDate}</th> 
                                 </tr>`
        
                                    $('#inquiryList').append(temp_html)
                                }
                                alert("조회 성공");
                            }).fail(function (response) {
                                console.log(response.responseJSON);
                                if (response.responseJSON.statusCode === 403) {
                                    alert(response.responseJSON.message)
                                }
                            });
                    }
                </script>         

※ 입력값이 들어가면 어떠한 코드를 통해 어떠한 값으로 변화하는지

  1. 코드를 작성하며 발견된 버그오류는 어떠한게 있었는지 그리고 어떻게 해결하였는지.
  • 페이지번호 클릭시 해당 페이지로 이동할 수 있게 구현했는데 , 되지않아
    html을 두개로 만들어 하나는 첫페이지 (대문페이지) 로 두고 , 이동할때 사용하는 페이지를 만듬으로써 하이퍼링크에서 값을 받아 원하는 페이지로 이동 가능해졌다.

  • 선택한 페이지 보다 더 빈페이지 수가 만들어지는 에러 발생으로, 값을 치환해주는 함수 등을 추가했다.

if(totalPage < page){
    page = totalPage;
}
if(endPage>totalPage){
   endPage = totalPage
}
profile
개발자꿈나무

0개의 댓글