简体   繁体   English

如何使用JSTL增加循环变量?

[英]How to increment a loop variable with JSTL?

I want to do with the jstl something like this: 我想用jstl做这样的事情:

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 这是否可以与jstl一起使用?当我尝试这个时它会让我发现错误,我想知道是否有正确的方式来编写它

Not directly, but you can use the varStatus to put an instance of LoopTagStatus in the scope of <c:forEach> . 不是直接的,但你可以使用varStatus把实例LoopTagStatus在范围<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. 它提供了几个getter来解决循环索引以及它是循环的第一次还是最后一次迭代。

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:if>有意义,但我认为你实际上有两个相同大小的列表,其中包含评论名称和评论率,你需要只显示与评论​​相同的索引率。

<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. 更好的是创建一个具有namerate属性的Comment对象。

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: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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