How to break a foreach loop?

Hi guys,

How can I break a foreach loop if i got the following code:

<c:forEach items="${stuff.stuffPostingImages}" var="img" varStatus="imgstatus">
<c:if test="${img.sequence=='1'}">
<c:out value="${img.imagePath}" />
</c:if>
</c:forEach>


mean once img.sequence==1 then will print out then exit the loop. Please help, Thanks !

Yes you can manually code a <% break %> statement in there, but I consider that ugly, and unreliable.

hi, when u said no guarantee, does it mean sometimes it will break the loop and sometimes doesn't??

It either works or it won't. If it doesn't work the first time, it won't at all.

The whole thing depends on what code the container will generate from the JSTL syntax. Remember that the whole JSP gets turned into a java servlet. (.java file) Scriptlet code is just your way of putting your own stuff directly into that servlet.

A forEach tag will probably get turned into a loop
<% break; %> will always break from the current innermost loop.

However if the generated code has put another loop in there (who knows why?) then it might not work. It all depends on the code generated to run the tag. Thats why I said it is ugly.

JSTL does not have a break statement. I don't believe it needs one.
If what you really want is to retrieve one specific item from a list, and print it out, then write a method on your bean which will loop through, find that item and return it to JSTL where you can print it.
The JSTL is designed for display. Using the loop/control structures for programming logic defeats the whole purpose.

Just my 2cents anyway. The less scriptlet code the better, and putting in a hack like <% break; %> just goes against my sensibilities.

[url]https://forums.oracle.com/message/5912353[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值