How to filter recent entries using JSP c: forEach and c: if?

I am trying to develop a Spring MVC application with JSP pages and I am having a problem. This is more a problem of creativity than a problem with code, but it says:

Thus, the application basically receives the recipe (fields "Name", "Description of the problem", "Problem solving", etc.) and deletes the identifier on it as it is created.

I want to show the last 3 recipes created on the first page. I came up with a code that apparently shows the first 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 create last <3 recipes instead?

+4
source share
3 answers

Use the fn:length() EL function to calculate the total number of recipes. Before using any EL function , we also need to import the necessary tag library .

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

Then we use <c:set> to set the common value as an attribute with the page area.

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

<c:forEach> allows you to get the loop counter using its varStatus attribute. The counter area is local to the loop, and it automatically expands for you. This loop counter starts at 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 the LoopTagStatus class to access the current iteration counter value in your EL element as ${varStatusVar.count} .

+5
source

no need to check length, just use

 <c:if test="${not status.last}"> 
+4
source

You can compare the current counter with the total collection size using ${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> 

Edit:

You will need to import fn first in order to use JSTL fn to use:

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

All Articles