JSTL foreach loop specifying items, begin and end tags with variable for flexibility

1.3k Views Asked by At

Why is it when I try to specify value for begin and end tags with variable for flexibility purposes, they always result to 0 (which is 1st index and thus outputs only 1 entry). [See code below]

<%
    int maxEntry = 10;
    int pageNumber = Integer.parseInt(request.getParameter("page"));
%>

<c:forEach items="${employees}" var="employee" begin="${maxEntry*(pageNumber-1)}" end="${maxEntry*pageNumber}">
    Employee <c:out value="${employees}"/><p>
</c:forEach>

but when I do it this way:

<c:forEach items="${employees}" var="employee" begin="0" end="10">
    Employee <c:out value="${employees}"/><p>
</c:forEach>

it works as expected, it outputs 10 entries. Please enlighten me. Thanks in advance ~

1

There are 1 best solutions below

0
mag On

LOL I got it. Somehow I figured how to make it work thru some more googling and reading manuals:

int pageNumber = pageNumber = Integer.parseInt(request.getParameter("page"));;
int maxEntry = 10; 

// setAttribute to be read by JSTL
pageContext.setAttribute("maxEntry", maxEntry);
pageContext.setAttribute("pageNumber", pageNumber);

P.S. - which I also figured it is a bad approach. I learned that you can as well do it this way:

<c:set var="maxEntry" value="${10}" />

<c:choose>
    <c:when test="${empty param.page}">
        <c:set var="pageNumber" value="${1}" />
    </c:when>
    <c:otherwise>
        <c:set var="pageNumber" value="${param.page}" />
    </c:otherwise>
</c:choose>