China Naming Network - Ziwei Dou Shu - How to get the dynamic key of the map through EL expression?

How to get the dynamic key of the map through EL expression?

In EL, the square bracket operator is used to retrieve the elements of arrays and collections. For collections that implement the java.util.Map interface, the square bracket operator uses the associated key to find the value stored in the map.

Specify the key in square brackets and return the corresponding value as the value of the expression. For example, the expression ${Map['key']} returns the value associated with the key in the map referenced by the map identifier.

When the value of the expression in the items attribute of forEach is java.util.Map, the type of the variable named in var is java.util.Map.Entry When var=entry, use the expression ${entry.key} to get the key name. Use the expression $ {entry.value} to get the value of each entry. This is because the java.util.Map.Entry object has getKey and getValue methods, and the expression language follows the naming convention of JavaBean.

& lt%

Map & ltString, string & gt map2 = newhashmap ();

map2.put("a "," hello world ");

Map2.put("b ","This is a map ");

request.setAttribute("map2 ",map 2);

% & gt

& ltbr & gt

Key-value pair traversal

& ltc:forEach var = " item " items = " $ { map 2 } " & gt;

$ { item.key } & gt$ { item.value } & ltbr & gt

& lt/c:forEach & gt;

Key traversal

& ltc:forEach var = " item " items = " $ { map 2 } " & gt;

$ { item.key } & ltbr & gt

& lt/c:forEach & gt;

Value traversal

& ltc:forEach var = " item " items = " $ { map 2 } " & gt;

$ { item.value } & ltbr & gt

& lt/c:forEach & gt;

& ltbody & gt

& ltbr & gt& ltbr & gt

& lt%

List & lt string & gtlist = new ArrayList & lt string & gt ();

list . add(" first ");

list . add(" second ");

List & lt string & gtlist2 = new ArrayList & lt string & gt ();

list 2 . add(" aaaaaa ");

list 2 . add(" bbbbbb ");

Map< string, list & lt string & gt> map = newhashmap ();

map.put("a ",list);

map.put("b ",list 2);

Request.setAttribute("map ",map);

% & gt

Get list values by keys and traverse the list.

& ltc:forEach var = " item " items = " $ { map[' a ']} " & gt;

$ { item } & ltbr & gt

& lt/c:forEach & gt; & ltbr & gt

& ltc:forEach var = " item " items = " $ { map[' b ']} " & gt;

$ { item } & ltbr & gt

& lt/c:forEach & gt; & ltbr & gt

The value in the map is a list, which directly traverses each item in the list.

& ltc:forEach var = " item " items = " $ { map } " & gt;

& ltc:forEach items = " $ { item . value } " var = " it " & gt;

$ { it } & ltbr & gt

& lt/c:forEach & gt;

& lt/c:forEach & gt;