我有请求属性“dataSetList”,它是对象数据集的列表。我通过 JSTL 显示其数据。那里一切都很好。
但是我对下面的 JSTL 代码不满意,因为有两个内部 forEach 语句。 FruitList 和 PriceList 包含完全相同数量的元素。所以我想要一个 forEach 来循环遍历它们的内容。但我不知道如何在 JSTL 中做到这一点。
有什么想法吗?
数据集对象
public class DataSet {
String group;
List<String> fruitList = new ArrayList<String>();
List<String> priceList = new ArrayList<String>();
}
为了清晰和完整
List<DataSet> dataSetList = new ArrayList<DataSet>();
// set all data here
request.setAttribute("dataSetList", dataSetList);
我想将两个内部 JSTL forEach 合二为一
<c:forEach items="${dataSetList}" var="dataSetVar">
${dataSetVar.group} <br/>
<c:forEach items="${dataSetVar.fruitList}" var="fruit">
${fruit}
</c:forEach>
<c:forEach items="${dataSetVar.priceList}" var="price">
${price}
</c:forEach>
</c:forEach>
最佳答案
您可以使用varStatus
属性来获取当前项目的索引:
<c:forEach items="${dataSetList}" var="dataSetVar">
${dataSetVar.group} <br/>
<c:forEach items="${dataSetVar.fruitList}" var="fruit" varStatus="loopCount">
<c:out value="${fruit}" />
<c:out value="${dataSetVar.priceList[loopCount.index]}" />
</c:forEach>
</c:forEach>
但请注意,您的版本和这个版本将给出不同的输出。通过这个循环,每次迭代都会打印两个列表中的元素。在代码中,首先打印 fruitList
中的所有元素,然后打印 priceList
中的所有元素。选择您想要的。
关于java - 将多个 JSTL forEach 循环合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23093200/