Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a loop variable with JSTL?

Tags:

java

jsp

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

like image 459
Nick Robertson Avatar asked Jun 02 '12 23:06

Nick Robertson


1 Answers

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:

  • Places where JavaBeans are used?
like image 161
BalusC Avatar answered Oct 30 '22 00:10

BalusC