This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes JSP and the fly likes JSTL question - forEach loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "JSTL question - forEach loop" Watch "JSTL question - forEach loop" New topic
Author

JSTL question - forEach loop

SANJAY KUMAR
Greenhorn

Joined: Mar 27, 2002
Posts: 25
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


SCJP, SCWCD , SCBCD
Merrill Higginson
Ranch Hand

Joined: Feb 15, 2005
Posts: 4864
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.


Merrill
Consultant, Sima Solutions
SANJAY KUMAR
Greenhorn

Joined: Mar 27, 2002
Posts: 25
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

Joined: Feb 15, 2005
Posts: 4864
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

Joined: Jan 10, 2002
Posts: 60752
    
  65

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.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JSTL question - forEach loop
 
Similar Threads
redirect not working
Pagination in jsp
Help required for forEach tag
EL + Custom Tag troubles
How can I c:set an int in my JSP?