복붙노트

[SPRING] Spring + Thymeleaf - 목록의 페이지 매김을 구현하는 방법

SPRING

Spring + Thymeleaf - 목록의 페이지 매김을 구현하는 방법

Spring + Thymeleaf를 사용하여 간단한 응용 프로그램을 개발 중입니다. 페이지 중 하나에서 페이지 매김을해야하는 항목 목록이 있습니다.

이상적으로 나는 단지 currPageNo (현재 페이지의 번호)와 numOfPages (총 페이지 수) 변수를 뷰에 보내고 나머지 작업은 거기서 완료 될 것입니다 (이것은 프리젠 테이션 문제이며 아무것도 가지고 있지 않습니다. 비즈니스 논리와 관련이 있음). 그러나 가장 깨끗한 솔루션을 사용하려면 먼저 컨트롤러에서 일부 계산을 수행해야하므로 작은 악으로 간주합니다.

나는 다음과 같은 형식으로 페이지 목록을 얻고 싶습니다.

<Prev | 1 | ... | 3 | 4 | 5 | 6 | 7 | ... | 15 | Next>

나는 단지 다음과 같은 해결책을 가지고 올 수 있었다. 그것은 작동하지만 나는 당신이 그것이 매우 지저분하고 정말로 읽기가 어렵다는 것에 동의 할 것이라고 믿습니다.

또한 currPageNo 및 numOfPages 외에도 뷰에 두 개의 변수를 추가해야했습니다. 이상적인 해결책은 그렇게 할 필요가 없다는 것입니다.

firstPageNo = Math.max(2, currPageNo - 2)
lastPageNo = Math.min(numOfPages - 1, currPageNo + 2)

내 코드의 현재 버전이 다음과 같습니다.

<ul>
    <li th:if="${currPageNo &gt; 1}">
        <a th:href="@{/items.html(pageNo = ${currPageNo - 1})}" href="">&lt; Prev</a>
    </li>
    <li th:class="${currPageNo == 1} ? 'selected'">
        <a th:href="@{/items.html(pageNo = 1)}" th:if="${currPageNo &gt; 1}" href="">1</a>
        <span th:if="${currPageNo == 1}">1</span>
    </li>
    <li th:if="${currPageNo &gt;= 5}">
        ...
    </li>
    <li th:each="pageNo : ${#numbers.sequence(firstPageNo, lastPageNo)}"  th:class="${currPageNo == pageNo} ? 'selected'">
        <a th:href="@{/items.html(pageNo = ${pageNo})}" th:if="${pageNo != currPageNo}" th:text="${pageNo}" href="">2</a>
        <span th:if="${pageNo == currPageNo}" th:text="${pageNo}">2</span>
    </li>
    <li th:if="${currPageNo &lt;= (numOfPages - 4)}">
        ...
    </li>
    <li th:class="${currPageNo == numOfPages} ? 'selected'">
        <a th:href="@{/items.html(pageNo = ${numOfPages})}" th:if="${currPageNo &lt; numOfPages}" th:text="${numOfPages}" href="">10</a>
        <span th:if="${currPageNo == numOfPages}" th:text="${numOfPages}">1</span>
    </li>
    <li th:if="${currPageNo &lt; numOfPages}">
        <a th:href="@{/items.html(pageNo = ${currPageNo + 1})}" href=""> Next &gt;</a>
    </li>
</ul>

다음 목록은 제가 가장 좋아하는 문제를 요약합니다. 나는 그 중 일부는 플랫폼에 내재되어 있지만 아직도 목록이 길어지고 코드가 지저분 해 보인다는 것을 알고 있습니다.

또한 코드의 품질을 향상시키는 방법에 대한 다른 제안도 환영합니다.

아마도이 질문은 코드 리뷰 사이트에 더 적합 할 것입니다. 그러나 Thymeleaf는 아직 작은 사용자 기반의 기술로 보이므로 Stack Overflow에 대한 합리적인 답변을 기대합니다. 스택 오버플로는 훨씬 더 큰 사용자를 보유하고 있습니다. 기초 (나는 믿는다).

그러나, 그러한 질문이 정말로 환영받지 못한다면, 필요한 조언을 얻을 수 있도록 그것을 닫지 말고 올바른 사이트로 이동하는 것을 고려하십시오.

해결법

  1. ==============================

    1.에 설명 된 솔루션과 유사합니다. http://www.javacodegeeks.com/2013/03/implement-bootstrap-pagination-with-spring-data-and-thymeleaf.html

    에 설명 된 솔루션과 유사합니다. http://www.javacodegeeks.com/2013/03/implement-bootstrap-pagination-with-spring-data-and-thymeleaf.html

    그러나 Spring Pageable 주위에 래퍼를 사용하지 않는다.

    <div class="table-pagination">
        <ul class="pagination">
            <li th:class="${contactsPage.number eq 0} ? 'disabled' : ''">
                <a th:if="${not contactsPage.firstPage}" th:href="@{${'/contacts'}(page=${contactsPage.number-1},size=${contactsPage.size})}">Previous</a>
                <a th:if="${contactsPage.firstPage}" href="javascript:void(0);">Previous</a>
            </li>
    
            <li th:each="pageNo : ${#numbers.sequence(0, contactsPage.totalPages - 1)}" th:class="${contactsPage.number eq pageNo}? 'active' : ''">
                <a th:if="${contactsPage.number  eq pageNo}" href="javascript:void(0);">
                    <span th:text="${pageNo + 1}"></span>
                </a>
                <a th:if="${not (contactsPage.number  eq pageNo)}" th:href="@{${'/contacts'}(page=${pageNo},size=${contactsPage.size})}">
                    <span th:text="${pageNo + 1}"></span>
                </a>
    
            </li>
            <li th:class="${contactsPage.number + 1 ge contactsPage.totalPages} ? 'disabled' : ''">
                <a th:if="${not contactsPage.lastPage}" th:href="@{${'/contacts'}(page=${contactsPage.number+1},size=${contactsPage.size})}">Next</a>
                <a th:if="${contactsPage.lastPage}" href="javascript:void(0);">Next</a>
            </li>
        </ul>
    </div>
    
  2. ==============================

    2.Ben Thurley의 솔루션이 또 다른 옵션입니다. 우리는 그것을 구현했으며 원활하게 작동합니다 : http://bthurley.wordpress.com/2012/07/18/spring-mvc-with-restful-datatables/

    Ben Thurley의 솔루션이 또 다른 옵션입니다. 우리는 그것을 구현했으며 원활하게 작동합니다 : http://bthurley.wordpress.com/2012/07/18/spring-mvc-with-restful-datatables/

    검색에 대한 필터 인수와 같은 항목 쌍이 없지만 PagingCriteria 개체를 통해 쉽게 추가 할 수 있으며 TableParamArgumentResolver에 추가해야합니다.

    public class TableParamArgumentResolver implements WebArgumentResolver {
    
        private static final String S_ECHO           = "sEcho";
        private static final String I_DISPLAY_START  = "iDisplayStart";
        private static final String I_DISPLAY_LENGTH = "iDisplayLength";
        private static final String I_SORTING_COLS   = "iSortingCols";
    
        private static final String I_SORT_COLS      = "iSortCol_";
        private static final String S_SORT_DIR       = "sSortDir_";
        private static final String S_DATA_PROP      = "mDataProp_";
        private static final String I_DATA_SEARCH    = "sSearch";
    
        public Object resolveArgument(MethodParameter param, NativeWebRequest request)
                throws Exception {
            TableParam tableParamAnnotation = param.getParameterAnnotation(TableParam.class);
    
            if (tableParamAnnotation != null) {
                HttpServletRequest httpRequest = (HttpServletRequest) request.getNativeRequest();
    
                String sEcho = httpRequest.getParameter(S_ECHO);
                String sDisplayStart = httpRequest.getParameter(I_DISPLAY_START);
                String sDisplayLength = httpRequest.getParameter(I_DISPLAY_LENGTH);
                String sSortingCols = httpRequest.getParameter(I_SORTING_COLS);
                String sSearch = httpRequest.getParameter(I_DATA_SEARCH);
    
                Integer iEcho = Integer.parseInt(sEcho);
                Integer iDisplayStart = Integer.parseInt(sDisplayStart);
                Integer iDisplayLength = Integer.parseInt(sDisplayLength);
                Integer iSortingCols = Integer.parseInt(sSortingCols);
    
                List<SortField> sortFields = new ArrayList<SortField>();
                for (int colCount = 0; colCount < iSortingCols; colCount++) {
                    String sSortCol = httpRequest.getParameter(I_SORT_COLS + colCount);
                    String sSortDir = httpRequest.getParameter(S_SORT_DIR + colCount);
                    String sColName = httpRequest.getParameter(S_DATA_PROP + sSortCol);
                    sortFields.add(new SortField(sColName, sSortDir));
                }
    
                PagingCriteria pc = new PagingCriteria(iDisplayStart, iDisplayLength, iEcho, sortFields, sSearch);
    
                return pc;
            }
    
            return WebArgumentResolver.UNRESOLVED;
        }
    }
    
  3. ==============================

    3.나는 거의 준비가되어있다.

    나는 거의 준비가되어있다.

    <div class="tag-box tag-box-v7 text-justify">
        <div class="text-center">
            <ul class="pagination" th:with="elementsperpage=2, blocksize=10, pages=${page2th.Number}/${elementsperpage}, wholepages=${format.format(pages)},
    whole=(${page2th.Number}/${blocksize})+1, wholex=${format.format(whole)}, startnlockpage=${wholepages}*${blocksize+1}, endblockpage=${wholepages}*${blocksize+1}, 
    startpage=${wholex-1}*${blocksize}, endpage=(${wholex}*${blocksize})+1">
    
                <li>
                    <a th:if="${startpage gt 0}" th:href="@{${'/viewannouncements?p='}+${startpage}}">&lt;&lt;</a>
                    <a th:if="${startpage eq 0}" href="javascript:void(0);">&lt;&lt;</a>
                </li>
    
                <li th:each="pageNo : ${#numbers.sequence(endpage-11, (endpage lt page2th.TotalPages)? endpage-2 : page2th.TotalPages-1)}" 
                th:class="${page2th.Number eq pageNo}? 'active' : ''">
                        <a th:if="${page2th.Number eq pageNo}" href="javascript:void(0);">
                            <span th:text="${pageNo + 1}"></span>
                        </a>
                        <a th:if="${not (page2th.Number  eq pageNo)}" th:href="@{${'/viewannouncements?p='}+${pageNo+1}}">
                            <span th:text="${pageNo + 1}"></span>
                        </a>
                </li>
    
                <li>
                    <a th:if="${(endpage*elementsperpage) le (page2th.TotalElements)}" th:href="@{${'/viewannouncements?p='}+${endpage}}">&gt;&gt;</a>
                    <a th:if="${(endpage*elementsperpage) le (page2th.TotalElements)}" href="javascript:void(0);"></a>
                </li>
    
    
    
            </ul>
        </div>
    </div>
    
  4. from https://stackoverflow.com/questions/18490820/spring-thymeleaf-how-to-implement-pagination-for-a-list by cc-by-sa and MIT license