使用JSTL从ArrayList获取对象索引

时间:2011-11-24 04:36:09

标签: jsp arraylist jstl

是否可以使用JSTL从arraylist获取“row”索引?

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

我的目的是设置一个超链接,其中包含每行上的每个项目ID,以便用户可以单击并显示弹出窗口或其他页面,并轻松地从arraylist中检索单个对象,而无需返回到数据库并设置另一个会话对象等。

2 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:0)

找出解决方案:

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

如果有人知道更优雅的方法,我会很高兴看到它。