8

我想用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> 

这对 jstl 可行吗?当我尝试这个时,它击中了我的错误,我想知道是否有正确的方法来编写它

4

1 回答 1

9

不是直接的,但您可以使用varStatus将 的实例LoopTagStatus放在 的范围内<c:forEach>。它提供了几个 getter 来计算循环索引以及它是循环的第一次还是最后一次迭代。

我只是不确定你的<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> 

然而,这很笨拙。您可以直接按索引更好地获取费率。

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

更好的是创建一个Comment具有nameandrate属性的对象。

public class Comment {

    private String name;
    private Integer rate;

    // Add/autogenerate getters/setters.
}

这样您就可以按如下方式使用它:

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

也可以看看:

于 2012-06-02T23:17:27.980 回答