Access map value in EL using a variable as key

2019-03-10 06:50发布

I have a Map in EL as ${map} and I am trying to get the value of it using a key which is by itself also an EL variable ${key} with the value "1000".

Using ${map["1000"]} works, but ${map["$key"]} does not work. What am I doing wrong and how can I get the Map value using a variable as key?

标签: jsp el
4条回答
Anthone
2楼-- · 2019-03-10 07:37

$ is not the start of a variable name, it indicates the start of an expression. You should use ${map[key]} to access the property key in map map.

You can try it on a page with a GET parameter, using the following query string for example ?whatEver=something

<c:set var="myParam" value="whatEver"/>
whatEver: <c:out value="${param[myParam]}"/>

This will output:

whatEver: something

See: https://stackoverflow.com/tags/el/info and scroll to the section "Brace notation".

查看更多
成全新的幸福
3楼-- · 2019-03-10 07:42

You can put the key-value in a map on Java side and access the same using JSTL on JSP page as below:

Prior java 1.7:

Map<String, String> map = new HashMap<String, String>();
map.put("key","value");

Java 1.7 and above:

Map<String, String> map = new HashMap<>();
map.put("key","value");

JSP Snippet:

<c:out value="${map['key']}"/>
查看更多
疯言疯语
4楼-- · 2019-03-10 07:48

I think that you should access your map something like:

${map.key}

and check some tutorials about jstl like 1 and 2 (a little bit outdated, but still functional)

查看更多
叛逆
5楼-- · 2019-03-10 07:52

I have faced this issue before. This typically happens when the key is not a String. The fix is to cast the key to a String before using the key to get a value from the map

Something like this:

<c:set var="keyString">${someKeyThatIsNotString}</c:set>

<c:out value="${map[keyString]}"/>

Hope that helps

查看更多
登录 后发表回答