Get object index from ArrayList using JSTL

Is it possible to get the row index from an array using JSTL?

<c:forEach items="${searchResults}" var="contact">
<div style="padding: 5px;">
${contact.firstName} ${contact.lastName}
<br>
${contact.primaryPhone}
</div>
</c:forEach>

My intention is to set a hyperlink containing each identifier of the elements in each row so that the user can click and display a popup window or other page and easily retrieve only one object from the arraylist without returning to the database and setting up another session object and etc.

+5
source share
2 answers

Use attribute varStatus.

<c:forEach items="${searchResults}" var="contact" varStatus="loop">
  <div style="padding: 5px;">
  ${loop.index} - 
  ${contact.firstName} ${contact.lastName}
  <br>
  ${contact.primaryPhone}
 </div>
</c:forEach>
+10
source

It turned out the solution:

<c:set var="index" value="${0}"></c:set>
<c:forEach items="${searchResults}" var="contact">
<div style="padding: 5px;">
${contact.firstName} ${contact.lastName}
<br>
${contact.primaryPhone}
<br>
${index}
</div>
<c:set var="index" value="${index+1}"></c:set>
</c:forEach>

If someone knows a more elegant approach, I would be happy to see him.

0
source

All Articles