Java – Use JSTL forEach loop’s varStatus as an ID

eljavajspjstl

I want to use the count from the JSTL forEach loop, but my code doesnt seem to work.

<c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
    <div id="divIDNo${theCount}">
    </div>
</c:forEach>

produces

<div id="divIDNojavax.servlet.jsp.jstl.core.LoopTagSupport$1Status@5570e2" >

Best Answer

The variable set by varStatus is a LoopTagStatus object, not an int. Use:

<div id="divIDNo${theCount.index}">

To clarify:

  • ${theCount.index} starts counting at 0 unless you've set the begin attribute
  • ${theCount.count} starts counting at 1