根据jstl中的索引获取arraylist的元素

根据jstl中的索引获取arraylist的元素

本文介绍了根据jstl中的索引获取arraylist的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这也许是一件相对简单的事情,但是由于某些原因,我似乎做得不好.

This is perhaps a relatively simple thing to do but for some reason I don't seem to get it right.

如何基于索引从jstl的arrayList中获取元素.

How does one get an element from an arrayList in jstl based on an index.

在纯Java中,可以说我有这个讲坛的人

In pure java, lets say I have this arralist

ArrayList< String > colors = new ArrayList< String >();
   colors.add("red");
   colors.add("orange");
   colors.add("yellow");
   colors.add("green");
   colors.add("blue");

如果我这样做System.out.println(colors.get(1));我从基于arrayList的第一种颜色在我提供的索引上恰好是red.

if I do System.out.println(colors.get(1)); I get the first color from the arrayList basedon the index I supplied which happens to be red.

想知道如何在jstl中实现它.我在jstl中使用了foreach标记,但并没有完全正确.

Wondering how to achieve that in jstl. I played with the foreach tag in jstl but did not quite get it right.

<c:forEach items="colors" var="element">
 <c:out value="${element.get(1)}"/>
</c:forEach>

推荐答案

当您说colors.get(1);${element[1]}时,它实际上是指列表中的单个条目.但是,当您使用c:forEach时,它会循环.这取决于您要实现的目标.如果您只想要第N个元素,请尝试

When you say colors.get(1); or ${element[1]} its actually referrign to single entry in the list. But when you use c:forEach its iterating the loop.It depends on what you are trying to achieve. If you just want the Nth element try

<c:out value="${colors[1]}"/> // This prints the second element of the list

但是您想打印整个元素,就像这样循环

but rather you want to print the entire elements you should go for loop like

<c:forEach items="${colors}" var="element">
    <c:out value="${element}"/>
</c:forEach>

还请注意,如果您编写类似<c:forEach items="colors" var="element">的文字,则将其字面值视为"colors".因此,如果它是一个变量名,则需要像上例中的${colors}一样在${}中给它命名.

Also please note if you write like <c:forEach items="colors" var="element"> it literally treat the value as "colors". So if its a variable name you need to give it in ${} like ${colors} as depicted in example above.

这篇关于根据jstl中的索引获取arraylist的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:37