Right, I'm wondering if you could help me out with the syntax in particular. For example, would i be able to do the following:
- Assume that myBean extends ArrayList
<c:forEach var="myArrayList" items="${mybean}">
<c:forEach var="myHashMap" items="${mybean.myMap}">
//How do i access a key, value pair in this map?
</c:forEach>
</c:forEach>
Thanks for the help.
[nobr]Based on this example:
MyBeanpublic List< Map<String, String> > getArrayList() {
List< Map<String, String> > arrayList = new ArrayList< Map<String, String> >();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1a");
map1.put("key2", "value2a");
arrayList.add(map1);
Map<String, String> map2 = new HashMap<String, String>();
map2.put("key1", "value1b");
map2.put("key2", "value2b");
arrayList.add(map2);
return arrayList;
}
If you know the key names before:<c:forEach items="${myBean.arrayList}" var="hashMap">
key1 value: <c:out value="${hashMap.key1}" />
key2 value: <c:out value="${hashMap.key2}" />
<br />
</c:forEach>
If you don't know the key names before and just want all entries:<c:forEach items="${myBean.arrayList}" var="hashMap">
<c:forEach items="${hashMap}" var="entry">
key: <c:out value="${entry.key}" />
value: <c:out value="${entry.value}" />
<br />
</c:forEach>
<br />
</c:forEach>
Note: remove spaces from generic type parameter if you're about to copypasting this. This forum doesn't parse nested < and > tags correctly.[/nobr]
[nobr]Ok. I do know my key names...they are defined as constants inside of a java file. Can I access constants defined in a java file using EL? Also, with your example below:
<c:forEach items="${myBean.arrayList}" var="hashMap">
key1 value: <c:out value="${hashMap.key1}" />
key2 value: <c:out value="${hashMap.key2}" />
<br />
</c:forEach>
- Sorry for the dumb question, but how come ${myBean.arrayList} isn't referring to the ArrayList and NOT the hashMap?[/nobr]
The standard for a forEach loop is
<c:forEach var="item" items="${myListOfItems}>
Given your description above myBean IS an List (extends ArrayList) of HashMaps. So the expression should be ${myBean} rather than ${myBean.arrayList}
<c:forEach var="hashMap" items="${myBean}" >
This loop is saying go through the list "myBean", and on each iteration store the value in the variable "hashMap"
Inside this loop, you no longer need to refer to "myBean" but just to the element "hashMap".