Java JSTL 计算 ForEach 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21599133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:35:58  来源:igfitidea点击:

JSTL Count the ForEach loop

javajspforeachjstl

提问by Reddy

I am trying to print some message for every 4 items in the List of items

我正在尝试为项目列表中的每 4 个项目打印一些消息

<c:forEach items="${categoryList}" var="category" varStatus="i">
    <c:if test="${i%4 == 0}">
        <c:out value="Test" />
    </c:if>
    <div class="span3">
        <c:out value="a" />
    </div>
</c:forEach>

But I am getting below exceptions, seems like iis not treated as number

但是我遇到了例外情况,似乎i没有被视为数字

java.lang.IllegalArgumentException: Cannot convert javax.servlet.jsp.jstl.core.LoopTagSupportStatus@3371b822 of type class javax.servlet.jsp.jstl.core.LoopTagSupportStatus to Number
    at org.apache.el.lang.ELArithmetic.coerce(ELArithmetic.java:407)
    at org.apache.el.lang.ELArithmetic.mod(ELArithmetic.java:291)
    at org.apache.el.parser.AstMod.getValue(AstMod.java:41)
    at org.apache.el.parser.AstEqual.getValue(AstEqual.java:38)

How do I achieve this?

我如何实现这一目标?

One way is to declare a variable and increment for every loop with the help of scriplets. But I would like to avoid this!

一种方法是在脚本的帮助下为每个循环声明一个变量和增量。但我想避免这种情况!

采纳答案by Rohit Jain

The variable iis of type LoopTagStatus. To get an int, you can use getCount()or getIndex().

变量i的类型为LoopTagStatus。要获得int,您可以使用getCount()getIndex()

If you want to print message for 1stitem, then use:

如果您想打印消息1项目,然后使用:

<!-- `${i.index}` starts counting at 0 -->
<c:if test="${i.index % 4 == 0}">  
    <c:out value="Test" />
</c:if>

else use:

否则使用:

<!-- `${i.count}` starts counting at 1 -->
<c:if test="${i.count % 4 == 0}">
    <c:out value="Test" />
</c:if>

回答by user1983983

varStatusis of the type LoopTagStatus(JavaDoc). So you have to use the property countof i:

varStatus是类型LoopTagStatus( JavaDoc)。所以,你必须使用属性counti

<c:if test="${i.count % 4 == 0}">
    <c:out value="Test" />
</c:if>