我想用 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 来说可能吗?当我尝试这个时它给我带来了错误,我想知道是否有正确的方式来编写它
最佳答案
不是直接的,但是你可以使用 varStatus
放置 LoopTagStatus
的实例在<c:forEach>
的范围内.它提供了几个 setter/getter 来计算循环index。以及它是否是 first或 last循环的迭代。
我只是不确定你的 <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
带有 name
的对象和 rate
属性(property)。
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>
另见:
关于java - 如何使用 JSTL 增加循环变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866608/