如何使用JSTL forEach循环迭代HashMap?

时间:2012-02-13 08:05:48

标签: jsp hashmap

在我的Spring MVC应用程序中,我从controllerServlet返回了HashMap。现在我需要使用JSTL在我的jsp中打印它。请帮忙。我是这一切的新手。

2 个答案:

答案 0 :(得分:39)

试试这个,

假设我的MAP是: -

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);

所以在JSP中,

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

希望这有帮助!

答案 1 :(得分:7)

要从哈希映射访问动态值,您可以使用括号表示法[]

${someMap[dynamicKey]}  

例如,考虑@Som's答案地图

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

设置密钥

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

传递动态密钥

${countryMap[keyName]}

或直接

${countryMap['United States']}  

另见