How to iterate HashMap using JSTL forEach loop? [d

2019-01-09 10:16发布

This question already has an answer here:

In my Spring MVC application i have HashMap returned from my controllerServlet. Now I need to print that in my jsp using JSTL. Please help on this. I'm new in all this.

标签: jsp hashmap
2条回答
在下西门庆
2楼-- · 2019-01-09 10:35

Try this,

suppose my MAP is :-

Map<String, String> countryList = new HashMap<String, String>();
countryList.put("United States", "Washington DC");
countryList.put("India", "Delhi");
countryList.put("Germany", "Berlin");
countryList.put("France", "Paris");
countryList.put("Italy", "Rome");

request.setAttribute("capitalList", countryList);

So in JSP ,

<c:forEach var="country" items="${capitalList}">
    Country: ${country.key}  - Capital: ${country.value}
</c:forEach>

Hope this helps !

查看更多
Summer. ? 凉城
3楼-- · 2019-01-09 10:47

For accessing dynamic value from hash map you can use brace notation [].

${someMap[dynamicKey]}  

For example, consider @Som's answer map

Map<String, String> countryMap = new HashMap<String, String>();
countryMap.put("United States", "Washington DC");
countryMap.put("India", "Delhi");
countryMap.put("Germany", "Berlin");
countryMap.put("France", "Paris");
countryMap.put("Italy", "Rome");

request.setAttribute("countryMap", countryMap);  

JSP

Set key

<c:set var="keyName" value="India" />  

pass the dynamic key

${countryMap[keyName]}

Or directly

${countryMap['United States']}  

See also

查看更多
登录 后发表回答