【问题标题】:How to iterate HashMap using JSTL forEach loop? [duplicate]如何使用 JSTL forEach 循环迭代 HashMap? [复制]
【发布时间】:2012-03-04 15:52:12
【问题描述】:

在我的 Spring MVC 应用程序中,我从我的 controllerServlet 返回了 HashMap。现在我需要使用 JSTL 在我的 jsp 中打印它。请帮助解决这个问题。我对这一切都很陌生。

【问题讨论】:

    标签: jsp hashmap


    【解决方案1】:

    试试这个,

    假设我的地图是:-

    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>
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      要从哈希映射中访问动态值,您可以使用大括号符号[]

      ${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']}  
      

      另见

      【讨论】:

        猜你喜欢
        • 2014-08-25
        • 2013-11-19
        • 2016-02-03
        • 1970-01-01
        • 1970-01-01
        • 2011-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多