• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JSTL question - forEach loop

 
SANJAY KUMAR
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friend,
I have a collection of object, I need to reiterate it max 3 times or less (if collection size is less than 3).

I wrote code like this but I am getting error in end field should be integer. Can some one throw light how to do it.
Please let me know if this code is right or I can do it another way.

<c:set var="listSize" value="${fn:length(testCollection)-1}"/>
<c:if test="${listSize > 3}">
<c:set var="listSize" value="3"/>
</c:if>

<c:forEach items='${testCollection}' end='${listSize}' var="test">
</c:forEach>

Thanks
 
Merrill Higginson
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't have to worry about a case where the size of the collection is smaller than 3. If the end of the collection is reached, the iterator will stop regardless of whether it has reached the end index.

Try it like this:

<c:forEach items='${testCollection}' begin="0" end="2" var="test">
</c:forEach>

This will iterate no more than 3 times, but less than 3 if the size if the collection is smaller than 3 elements.
 
SANJAY KUMAR
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply.

My understanding is if I use begin='0' and end='2' my loop will go 3 time if even if my collection size is one.

Is that true or not.

Can you please clarify?


Thanks
 
Merrill Higginson
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by SANJAY KUMAR:
My understanding is if I use begin='0' and end='2' my loop will go 3 time if even if my collection size is one.

That is not true. As I said before, if the end of the collection is reached, the iterator will stop. Try it yourself, and you'll see.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65216
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please do our eyes a favor and modify your display name to mixed ro lower case. Thanks.

If you want the loop to exectue three times regardless of the size of the collection, use the begin and end attributes but not items.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic