在JSP中循环HashSet和HashMap并打印结果

时间:2013-01-30 20:51:51

标签: java jsp spring-mvc

我想从for loop开始在JSP中执行以下操作 - 我只想循环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)

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:4)

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

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