jstl输出HashMap的结果 C:foreach

JavaServer Tag library is one of the most used JSP tag library out there. I have used it almost in all of my JEE based projects. The best feature probably is the Iterator API in JSTL tag library.

Here is a small code snippet which you might not know. Its very easy to iterate Lists using JSTL. For example:

//Java
List<String> cityList =newArrayList<String>();
cityList.add("Washington DC");
cityList.add("Delhi");
cityList.add("Berlin");
cityList.add("Paris");
cityList.add("Rome");
 
request.setAttribute("cityList", cityList);
 
 
//JSP
<c:forEach var="city"items="cityList">
    <b> ${city} </b>
</c:forEach>

But what if you want to iterate a Hashmap? Well that too is piece of cake. Here is the example:

//Java
Map<String, String> countryCapitalList =newHashMap<String, String>();
countryCapitalList.put("United States","Washington DC");
countryCapitalList.put("India","Delhi");
countryCapitalList.put("Germany","Berlin");
countryCapitalList.put("France","Paris");
countryCapitalList.put("Italy","Rome");
         
request.setAttribute("capitalList", countryCapitalList);
 
//JSP
<c:forEach var="country"items="${capitalList}">
    Country: ${country.key}  - Capital: ${country.value}
</c:forEach>

Happy iterating :-)

你可能感兴趣的:(jstl输出HashMap的结果 C:foreach)