How to break a foreach loop?

阅读更多
Hi guys,

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







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.

https://forums.oracle.com/message/5912353

你可能感兴趣的:(jsp)