简体   繁体   中英

How to increment a loop variable with JSTL?

I want to do with the jstl something like this:

int i=0;
int j=0;

<c:forEach items="${commentNames}" var="comment">     

     <c:forEach items="${rates}" var="rate">

        <c:if test="${i==j}">

          int i++

        </c:if> 

     </c:forEach> 

  int j++;

</c:forEach> 

Is this possible with the jstl?When i try this it hit me errors and i was wondering if there is a correct way way to write it

Not directly, but you can use the varStatus to put an instance of LoopTagStatus in the scope of <c:forEach> . It offers several getters to figure among others the loop index and whether it's the first or the last iteration of the loop.

I'm only unsure how your <c:if> makes sense, but I think that you actually have two lists of the same size with comment names and comment rates and that you need to show only the rate at the same index as the comment.

<c:forEach items="${commentNames}" var="comment" varStatus="commentLoop">     
    ${comment}
    <c:forEach items="${rates}" var="rate" varStatus="rateLoop">
        <c:if test="${commentLoop.index == rateLoop.index}">
            ${rate}
        </c:if>
    </c:forEach> 
</c:forEach> 

This is however clumsy. You can better get the rate by index directly.

<c:forEach items="${commentNames}" var="comment" varStatus="commentLoop">     
    ${comment}
    ${rates[commentLoop.index]}
</c:forEach> 

Much better is to create a Comment object with a name and rate property.

public class Comment {

    private String name;
    private Integer rate;

    // Add/autogenerate getters/setters.
}

So that you can use it as follows:

<c:forEach items="${comments}" var="comment">
    ${comment.name}
    ${comment.rate}
</c:forEach> 

See also:

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