这可能是一件相对简单的事情,但由于某种原因,我似乎没有做对.
如何根据索引从jstl中的arrayList获取元素.
在纯java中,让我说我有这个arralist
ArrayList< String > colors = new ArrayList< String >();
colors.add("red");
colors.add("orange");
colors.add("yellow");
colors.add("green");
colors.add("blue");
Run Code Online (Sandbox Code Playgroud)
如果我这样做,System.out.println(colors.get(1));我会根据我提供的索引从arrayList中获取第一个颜色red.
想知道如何在jstl中实现这一点.我在jstl玩了foreach标签但是没有完全正确.
<c:forEach items="colors" var="element">
<c:out value="${element.get(1)}"/>
</c:forEach>
Run Code Online (Sandbox Code Playgroud)
Sya*_*m S 18
当您说colors.get(1);或其${element[1]}实际引用列表中的单个条目时.但是当你使用c:forEach它迭代循环时.这取决于你想要达到的目标.如果你只想要第N个元素试试
<c:out value="${colors[1]}"/> // This prints the second element of the list
Run Code Online (Sandbox Code Playgroud)
但是你想要打印你应该循环的所有元素
<c:forEach items="${colors}" var="element">
<c:out value="${element}"/>
</c:forEach>
Run Code Online (Sandbox Code Playgroud)
另请注意,如果你写的话就像 <c:forEach items="colors" var="element">字面意思一样对待价值"colors".因此,如果它是一个变量名,你需要${}像${colors}上面的例子中描述的那样给它.
| 归档时间: |
|
| 查看次数: |
57319 次 |
| 最近记录: |