is it possible to iterate two items simultaneously using foreach in jstl?

北城余情 提交于 2019-12-17 22:42:38

问题


I have two items from my model and I want to iterate them at the same using jstl foreach. how can I achieve this using a correct syntax?


回答1:


You can call varStatus.index to get the index of the current round of iteration, and then use it as a lookup for the second list.

For example, if you have two lists people.firstnames and people.lastnames you can do:

<c:forEach var="p" items="${people.firstnames}" varStatus="status">
  <tr>
      <td>${p}</td>
      <td>${people.lastnames[status.index]}</td>
  </tr>
</c:forEach>



回答2:


I assume you have to collections that you want to iterate in one go. Add a getter which will merge these two collections and use it for the iteration. For example

private Collection<String> first;
private Collection<String> second;

public Collection<String> getBoth()
{
  List<String> result = new ArrayList<String>();
  result.addAll(first);
  result.addAll(second);
  return result;
}

Iteration in JSTL:

<c:forEach var="p" items="${people.both}">
  <tr>
      <td>${p}</td>
  </tr>
</c:forEach>


来源:https://stackoverflow.com/questions/4142631/is-it-possible-to-iterate-two-items-simultaneously-using-foreach-in-jstl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!