Search code examples
javajspspring-mvcjstl

How to filter last entries with JSP c:forEach and c:if?


I'm trying to develop a Spring MVC application with JSP pages and I've run into a problem. It's more of a creativity problem than a code problem, but here goes:

So the application basically recieves a recipe (fields Name, Problem Description, Problem Solution, etc) and slaps an ID on it as it is created.

What I want is to show on the front page the last 3 recipes created. I've come up with a code that apparently shows the first 3 recipes created:

<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>

Any ideas on how to show the last 3 recipes created instead?


Solution

  • Use the fn:length() EL function to calculate the total number of recipes. Before we use any EL function we need to import the necessary tag library as well.

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

    Then we use <c:set> to set the total as a page-scoped attribute.

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

    <c:forEach> allows you to get a loop counter using its varStatus attribute. The counter's scope is local to the loop and it increments automatically for you. This loop counter starts counting from 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>
    

    EDIT: Use the count property of LoopTagStatus class to access the current value of the iteration counter in your EL as ${varStatusVar.count}.