如何使用JSP c:forEach和c:if过滤最后的条目?

问题描述 投票:4回答:3

我正在尝试使用JSP页面开发Spring MVC应用程序,但我遇到了一个问题。它更像是一个创造性问题,而不是一个代码问题,但是这里有:

因此,应用程序基本上收到一个配方(字段名称,问题描述,问题解决方案等),并在创建时在其上拍一个ID。

我想要的是在头版上显示最后创建的3个食谱。我想出了一个显然显示前3个食谱的代码:

<c:forEach var="recipe" items='${recipes}'>
    <c:if test="${recipe.id < 4}
        <div class="span4">
            <h3<c:out value="${recipe.inputDescProb}"></c:out></h3>
            <p><c:out value="${recipe.inputDescSol}"></c:out></p>
            <p><a class="btn" href="/recipes/${recipe.id}">Details &raquo</a></p>
        </div>
    </c:if>
</c:forEach>

有关如何显示最后3个食谱的想法吗?

java jsp spring-mvc jstl
3个回答
5
投票

使用fn:length() EL函数计算配方总数。在我们使用任何EL function之前,我们还需要导入必要的tag library

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

然后我们使用<c:set>将总数设置为页面范围属性。

<c:set var="totalRecipes" value="${fn:length(recipes)}" />

<c:forEach>允许您使用其varStatus属性获取循环计数器。计数器的范围是循环的本地范围,它会自动递增。这个loop counter从1开始计算。

<c:forEach var="recipe" items='${recipes}' varStatus="recipeCounter">
  <c:if test="${recipeCounter.count > (totalRecipes - 3)}">
    <div class="span4">
      <h3<c:out value="${recipe.inputDescProb}"></c:out></h3>
      <p><c:out value="${recipe.inputDescSol}"></c:out></p>
      <p><a class="btn" href="/recipes/${recipe.id}">Details &raquo;</a></p>
    </div>
  </c:if>
</c:forEach>

编辑:使用count类的LoopTagStatus属性来访问EL中迭代计数器的当前值${varStatusVar.count}


5
投票

无需检查长度,只需使用.last变量的varStatus属性。

<c:forEach var="recipe" items="${recipes}" varStatus="status">
  <c:if test="${not status.last}">
    Last Item
  </c:if>
<c:forEach>

旁注,你也可以得到.first.count


1
投票

您可以使用${fn:length(recipes)}将当前计数与总集合大小进行比较:

<c:set var="total" value="${fn:length(recipes)}"/>


<c:forEach var="recipe" items='${recipes}' varStatus="status">
  <c:if test="${status.count > total - 3}">
    <div class="span4">
      <h3<c:out value="${recipe.inputDescProb}"></c:out></h3>
      <p><c:out value="${recipe.inputDescSol}"></c:out></p>
      <p><a class="btn" href="/recipes/${recipe.id}">Details &raquo</a></p>
    </div>
  </c:if>
</c:forEach>

编辑:

您需要先导入fn以使JSTL fn可供使用:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
© www.soinside.com 2019 - 2024. All rights reserved.