【问题标题】:Loop through HashSet and HashMap in JSP and print the result循环遍历 JSP 中的 HashSet 和 HashMap 并打印结果
【发布时间】:2013-01-30 20:51:50
【问题描述】:

我想在 JSP 中从 for loop 开始做以下事情-我只想循环 HashSet 和 HashMap 并打印结果

private static HashMap<Long, Long> histogram = new HashMap<Long, Long>();
private static Set<Long> keys = histogram.keySet();

for (Long key : keys) {
    Long value = histogram.get(key);
    System.out.println("MEASUREMENT, HG data, " + key + ":" + value);
}

我正在使用 Spring MVC,所以我在 model 中添加了这两件事

model.addAttribute("hashSet", (keys));
model.addAttribute("histogram", (histogram));

在我的 JSP 页面中,我正在做类似的事情来模拟上面的 JAVA code 但它给了我一个例外,即我的 JSP 页面有问题。

<fieldset>
    <legend>Performance Testing:</legend>
        <pre>

            <c:forEach items="${hashSet}" var="entry">
            Key = ${entry.key}, value = ${histogram}.get(${entry.key})<br>
            </c:forEach>


        </pre>
        <br />
</fieldset>

我得到了例外-

Caused by: javax.el.PropertyNotFoundException: Property 'key' not found on type java.lang.Long
    at javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:195)
    at javax.el.BeanELResolver$BeanProperties.access$400(BeanELResolver.java:172)
    at javax.el.BeanELResolver.property(BeanELResolver.java:281)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:62)

谁能帮我解决这个问题?

【问题讨论】:

  • 在不知道异常的确切含义的情况下,没有人可以帮助您。 “出了点问题”信息不足以继续下去。
  • 编辑了问题。对不起那个理查德。

标签: java jsp spring-mvc


【解决方案1】:

您无需使用keySet 即可访问HashMap 中的values。当您使用&lt;c:forEach..> 迭代HashMap 时,您将返回EntrySet,您可以直接使用:-EntrySet#getKey()EntrySet#getValue():-

<c:forEach items="${histogram}" var="entry">
     Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>

【讨论】:

  • 感谢 Rohit 的帮助。请仔细看看我的问题。我猜我需要从 HashMap 中提取数据。你的部分回答对我来说很有意义
  • @TechGeeky.. 问题是,你不能在 JSTL 中调用这样的函数。所以,你不能调用map.get(key) 方法。为此,您必须创建一个自定义标签,该标签在某个 TagHandler 类中定义了一个自定义函数,该函数将返回您的 map.get(key) 值。这当然是一项更乏味的任务。
  • 我明白了.. 所以我想我可以直接迭代 HashMap 而不是使用 HashSet 对吗?
  • @TechGeeky .. 没错。看看我发布的 for 循环。它遍历 hashmap,并返回 EntrySet。然后你就可以使用它的 getKey() 和 getValue() 方法了。
猜你喜欢
  • 2010-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 2013-09-14
  • 2019-02-18
  • 1970-01-01
相关资源
最近更新 更多