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

11 jsp hashmap

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

Som*_*Som 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);
Run Code Online (Sandbox Code Playgroud)

所以在JSP中

<c:forEach var="country" items="${capitalList}">
    Country: ${country.key}  - Capital: ${country.value}
</c:forEach>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 !


Ani*_*rni 7

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

${someMap[dynamicKey]}  
Run Code Online (Sandbox Code Playgroud)

例如,考虑@Som的答案图

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);  
Run Code Online (Sandbox Code Playgroud)

JSP

设置键

<c:set var="keyName" value="India" />  
Run Code Online (Sandbox Code Playgroud)

传递动态密钥

${countryMap[keyName]}
Run Code Online (Sandbox Code Playgroud)

或直接

${countryMap['United States']}  
Run Code Online (Sandbox Code Playgroud)

也可以看看