Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 593
jsfrocha Avatar asked Dec 16 '22 11:12

jsfrocha


2 Answers

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

like image 100
Ravi K Thapliyal Avatar answered Jan 13 '23 03:01

Ravi K Thapliyal


No need to check length, just use the .last property of the varStatus variable.

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

Side note, you can also get the .first and .count

like image 26
dmlek Avatar answered Jan 13 '23 03:01

dmlek