【问题标题】:how to populate html table with hashmap k,v?如何用 hashmap k,v 填充 html 表?
【发布时间】:2016-02-08 13:29:05
【问题描述】:

我有一个带有 k v 的 hashmap,那里有一些 dup 键,比如:

123 富​​p>

123 咕

345ggg

567 kkk

我想用这个信息填充我的 html 表,即使有重复,所以我可以这样打印它:

for (Map.Entry<String, List<String>> entry : total.entrySet()) {
  for (String s : entry.getValue()) {
    System.out.println(entry.getKey() + " " + s);
  }
}

所以现在我该如何填充表格,我尝试了这样的方法:

<table id="ptable" border="1">

            <tr>
                    <td style="text-align: center;">ID</td>
                    <td style="text-align: center;">Month</td>
            </tr>
</table>

然后:

< c:forEach var="employeeHash" items="${employeeHash}" >
    <td>${employeeSkills.key.id}</td>
</c:forEach>

但我不知道如何获取每个键的值...

我希望最终结果看起来像:

关键值

123 kkk

123 后

345 lll

【问题讨论】:

  • 对不起,我不明白这个问题。 Hashmap 不打算接受重复的键,因此将您的 HashMap&lt;Integer, String&gt; 转换为 HashMap&lt;Integer, List&lt;String&gt;&gt; 确实是一个好的开始。但是我不明白阻塞点在哪里。
  • 阻塞点是如何在 jsp 文件中的 hashmap 上进行迭代并将其打印到 html。 @ArnaudDenoyelle
  • 此链接对您有帮助吗? stackoverflow.com/questions/1835683/… 你实际上需要嵌套 2 个 c:forEach :一个在 map.entrySet 上,另一个在 entry.getValue 上(这是一个列表)
  • 可能同样的问题:here,请检查
  • 另一个提示:你真的需要HashMap吗?有时,创建一个中间类会使您的代码更清晰。创建一个简单的Pair 类可以让您处理一个简单的List&lt;Pair&gt;

标签: java dictionary hashmap


【解决方案1】:

假设您的employeeObjMap 具有键和值。以下代码应该可以工作。

<table>
  <TH>Key</th>
  <TH>Value</th>
  <c:forEach items="${employeeObjMap }" var="current">
    <tr>
      <td><c:out value="${current.key}" /><td>
      <td><c:out value="${current.value}" /><td>
    </tr>
  </c:forEach>
</table>

【讨论】:

  • 我是否需要使用 request.getSession.setAttribute(myHashMap) 将我的 hashmap 发送到会话,然后我才能访问它?因为现在我不能
  • @Joe 您将收到您将发送的内容。
  • 你是什么意思,我将发送什么?
【解决方案2】:

你可以说你也想要这个值,就像这样:

<c:forEach var="employeeHash" items="${employeeHash}" >
    <td>${employeeSkills.key.id}</td>
    <td>${employeeSkills.value}</td>
</c:forEach>

看看这个链接:Use <c:forEach> with HashMap

【讨论】:

  • 虽然这可能会回答问题,但it would be preferable 在此处包含答案的基本部分,并提供链接以供参考。
  • 我是否需要使用 request.getSession.setAttribute(myHashMap) 将我的 hashmap 发送到会话,然后我才能访问它?因为现在我不能
【解决方案3】:

这应该是一个评论,但我没有足够的地方。请不要投票。

我不是 JSP 专家,但嵌套 2 个 foreach 应该可以解决问题:

<c:forEach var="entry" items="${map}" >
  <!-- entry.key is employee.key -->
  <!-- entry.value is employee.skills -->
  <c:forEach var="skillId" items="${entry.value}" >
    <tr>
      <td>${entry.key}</td>
      <td>${skillId}</td>
    </tr>
  </c:forEach>
</c:forEach>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2020-12-29
    • 2013-12-19
    相关资源
    最近更新 更多