简体   繁体   中英

JSTL Break out of loop

I am trying to retrieve 20 records from my list of friends with their name starting with 'J'. However, I realized there is no break in JSTL. So I tried to use a count to keep track of the records. I hit into error 'PWC6031: Unterminated <c:set tag'

<c:set var="count" value="0" scope="page">
    <c:forEach items="${friendsList}" var="user">
        <c:if test="${count < 20}">
            <c:set var="string1" value="${fn:substring(user.name, 0, 1)}" />
            <c:if test="${fn:startsWith(string1,'J')}">
                <tr>
                <td><c:out value="${user.name}" /></td>
                <td><img src='https://graph.facebook.com/<c:out value="${user.id}"/>/picture' />
                </td>
            </tr>
            </c:if>
        </c:if>
        <c:set var="count" value="${count + 1}" scope="page"/>
    </c:forEach>

Is there a way that I can retrieve the value from count variable? If not, is there an alternative way that I can break out of the loop to achieve what I want? Thanks.

After resolving the error that I hit, I managed to make use of the count variable to list what I wanted. I mixed up the ordering of my 'count' coding in my original coding. Here's what I have now, is working, thanks everyone for the helps!

<c:set var="count" value="0" scope="page" />
    <c:forEach items="${friendsList}" var="user">
        <c:if test="${count < 20}">
            <c:set var="string1" value="${fn:substring(user.name, 0, 1)}" />
            <c:if test="${fn:startsWith(string1,'J')}">
                <tr>
                    <td><c:out value="${user.name}" /></td>
                    <td><img src='https://graph.facebook.com/<c:out value="${user.id}"/>/picture' /></td>
                </tr>
                <c:set var="count" value="${count + 1}" scope="page" />
            </c:if>
        </c:if>
    </c:forEach>

You're making it more difficult than necessary. Here are alternative solutions that are all better than yours, IMO, from the worst to the best one:

  1. Use the varStatus="loopStatus" attribute of c:forEach which allows knowing the index of the iteration inside the loop using ${loopStatus.index} . This allows removing your count attribute.
  2. Use the end="19" attribute of c:forEach
  3. Prepare the list in your controller (or even in your SQL query, when retrieving the users) to make sure it has only 20 elements max:

     users = users.subList(0, Math.min(users.size(), 20)); 

The issue seems to be with your first line. You have not terminated the c:set tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM