JSTL中的foreach循环中使用continue和break

27

我想在JSTL的foreach中插入"continue"。请告诉我是否有方法可以实现这一点。

<c:forEach 
  var="List"
  items="${requestScope.DetailList}" 
  varStatus="counter"
  begin="0">

  <c:if test="${List.someType == 'aaa' || 'AAA'}">
    <<<continue>>>
  </c:if>

我希望将"continue"命令放在if语句中。

4个回答

34

这并不存在。只需对您实际想要显示的内容进行反转即可。因此不要执行

操作。

<c:forEach items="${requestScope.DetailList}" var="list">
    <c:if test="${list.someType eq 'aaa' or list.someType eq 'AAA'}">
        <<<continue>>>
    </c:if>
    <p>someType is not aaa or AAA</p>
</c:forEach>

而是执行

<c:forEach items="${requestScope.DetailList}" var="list">
    <c:if test="${not (list.someType eq 'aaa' or list.someType eq 'AAA')}">
        <p>someType is not aaa or AAA</p>
    </c:if>
</c:forEach>
或者
<c:forEach items="${requestScope.DetailList}" var="list">
    <c:if test="${list.someType ne 'aaa' and list.someType ne 'AAA'}">
        <p>someType is not aaa or AAA</p>
    </c:if>
</c:forEach>

请注意,我还修正了您代码中的一个EL语法错误。


+1 啊 - 现在我明白她为什么想要使用 continue 了。BalusC 对问题的解释很好! - CoolBeans
1
我无法进行反向操作。因为我在循环中执行了一些操作。如果这个条件通过,我想停止它。如果这个条件通过,我想继续下一个迭代。感谢您的回答。如果没有使用 continue 语句跳转到下一个迭代的方法,我将尝试使用其他逻辑。 - Nazneen
我将条件取反了,现在它可以正常工作了。非常感谢您的回复和支持。 - Nazneen

5

我通过在可执行代码末尾和循环内使用Set解决了这个问题。

<c:set var="continueExecuting" scope="request" value="false"/>

然后我使用了该变量来跳过下一次迭代中的代码执行

<c:if test="${continueExecuting}">

你可以在任何时候将其设置回true...

<c:set var="continueExecuting" scope="request" value="true"/>

更多关于这个标签的信息请查看:JSTL Core 标签

祝你愉快!


4

或者你可以使用EL的choose语句

<c:forEach 
      var="List"
      items="${requestScope.DetailList}" 
      varStatus="counter"
      begin="0">

      <c:choose>
         <c:when test="${List.someType == 'aaa' || 'AAA'}">
           <!-- continue -->
         </c:when>
         <c:otherwise>
            Do something...     
         </c:otherwise>
      </c:choose>
    </c:forEach>

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接