5

Is it possible to get the "row" index from an arraylist 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 that contains each items ID on each row so the user can click and display a popup, or another page and easily retrieve just the single object from the arraylist without going back to the database and setting another session object etc.

2 Answers 2

11

Use varStatus attribute.

<c:forEach items="${searchResults}" var="contact" varStatus="loop">
  <div style="padding: 5px;">
  ${loop.index} - 
  ${contact.firstName} ${contact.lastName}
  <br>
  ${contact.primaryPhone}
 </div>
</c:forEach>
Sign up to request clarification or add additional context in comments.

Comments

0

Figured out a 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 anyone knows a more elegant approach, I would be happy to see it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.