Increment counter with loop

This question is related to my previous question :

Jsp iterate trough object list

I want to insert counter that starts from 0 in my for loop, I've tried several combinations so far :

1.

<c:forEach var="tableEntity" items='${requestScope.tables}'>
   <c:forEach var="rowEntity" items='${tableEntity.rows}' varStatus="count">            
        <c:out value="${count}" />
    </c:forEach>
</c:forEach>

2.

<c:set var="count" value="0" scope="page" />
<c:forEach var="tableEntity" items='${requestScope.tables}'>
   <c:forEach var="rowEntity" items='${tableEntity.rows}'>      
   <%=count++%>  
<c:out value="${count}" />
    </c:forEach>
</c:forEach>

Problem with first approach is that outer loop has 3 items and inner loop has 7 items, so for each outer item the count starts from 0. The second one I get compile error. Here is basically what I want :

counter = 0;
outer for loop 
    inner for loop 
       counter++;
       //cout/echo/print counter value should start from 0
    end inner loop
end outer loop

I'm just not totally familiar with the syntax. thank you


Solution 1:

Try the following:

<c:set var="count" value="0" scope="page" />

//in your loops
<c:set var="count" value="${count + 1}" scope="page"/>

Solution 2:

The varStatus references to LoopTagStatus which has a getIndex() method.

So:

<c:forEach var="tableEntity" items='${requestScope.tables}' varStatus="outer">
   <c:forEach var="rowEntity" items='${tableEntity.rows}' varStatus="inner">            
        <c:out value="${(outer.index * fn:length(tableEntity.rows)) + inner.index}" />
    </c:forEach>
</c:forEach>

See also:

  • Hidden features of JSP/Servlet

Solution 3:

You can use varStatus in your c:forEach loop

In your first example you can get the counter to work properly as follows...

<c:forEach var="tableEntity" items='${requestScope.tables}'>
   <c:forEach var="rowEntity" items='${tableEntity.rows}' varStatus="count">            
        my count is ${count.count}
    </c:forEach>
</c:forEach>