Tuesday, May 3, 2011

JSTL Pagination

The following code can be used to paginate database query results using JSTL.

The select statement results are stored in the queryResults variable. Here is the paginator code:

<c:set var="totalCount" scope="session" value="${queryResults.rowCount}"/>
    <c:set var="perPage" scope="session" value="20"/>
    <c:set var="totalPages" scope="session" value="${totalCount/perPage}"/>

    <c:set var="pageIndex" scope="session" value="${param.start/perPage+1}"/>

   <c:if test="${!empty param.start && param.start >(perPage-1) && param.start !=0 }">
          <a href="?start=<c:out value="${param.start - perPage}"/>">Prev </a>

    </c:if>

   <c:forEach
        var="boundaryStart"
        varStatus="status"
        begin="0"
        end="${totalCount - 1}"
        step="${perPage}">
        <c:choose>
            <c:when test="${status.count>0 && status.count != pageIndex}">
                             <a href="?start=<c:out value='${boundaryStart}'/>">

                                <c:out value="${status.count}"/> |
                            </a>
            </c:when>
        <c:otherwise>
                <c:out value="${status.count}"/> |
        </c:otherwise>

        </c:choose>
    </c:forEach>

    <c:if test="${empty param.start || param.start<(totalCount-perPage)}">
          <a href="?start=<c:out value="${param.start + perPage}"/>">Next </a>

    </c:if>

The code makes heavy use of the count property of the varStatus attribute.
This attribute keeps count of the current round of the iteration.