【问题标题】:JSTL Count the ForEach loopJSTL 计算 ForEach 循环
【发布时间】:2014-03-03 04:13:06
【问题描述】:

我正在尝试为项目列表中的每 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>

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

java.lang.IllegalArgumentException: Cannot convert javax.servlet.jsp.jstl.core.LoopTagSupport$1Status@3371b822 of type class javax.servlet.jsp.jstl.core.LoopTagSupport$1Status 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)

我如何实现这一目标?

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

【问题讨论】:

  • 你可以声明一个变量并使用jstl增加它

标签: java jsp foreach jstl


【解决方案1】:

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

如果您想为第 1 个st 项打印消息,请使用:

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

其他用途:

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

【讨论】:

【解决方案2】:

varStatus 的类型为 LoopTagStatus (JavaDoc)。所以你必须使用i的属性count

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

【讨论】:

    猜你喜欢
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多