【问题标题】:Access hashmap value by variable in JSP在 JSP 中通过变量访问 hashmap 值
【发布时间】:2011-01-25 10:37:51
【问题描述】:

我有一个hashmap,它被放到请求中:

HashMap<Integer, String> myMap = ...
request.setAttribute("myMap", myMap);

在 JSP 中我有一个 foreach 循环

<c:forEach items="${list}" var="item" varStatus="status">
   <c:out value="${item.description}"/>
   <c:out value="${myMap[item.id]}"/>
</c:forEach>

但是${myMap[item.id]} 不起作用。如何通过item.id变量访问hashmap的值?

【问题讨论】:

    标签: jsp hashmap el


    【解决方案1】:

    在 EL 中,数字被视为Long。将您的 Map 更改为 Map&lt;Long, String&gt; 即可。

    【讨论】:

    • HashMap&lt;String, some bean&gt; 是否有特殊情况,因为我尝试了这个${applicationscope.coursesHT[anotherbean.courseC]} 来获取当然的描述,但它没有用,但是当我使用c:setc:out 时它起作用了!! :) 谢谢
    【解决方案2】:

    我认为 beans 的 id 属性不是包装对象 (Integer id;)。查看Map的文档页面。

    来自 JavaDoc 的文本

    注意:如果出现以下情况,必须非常小心 可变对象用作映射键。 未指定地图的行为 如果一个对象的值改变了 以影响平等的方式 对象是键时的比较 在地图中。这种情况的一个特例 禁止是它不是 允许地图包含 本身作为一把钥匙。虽然它是 允许地图包含 本身作为一个价值,极端谨慎是 建议:equals 和 hashCode 方法不再被很好地定义在 一张这样的地图。

    Item.java

    package com.me;
    
    public class Item {
        private Integer id;
        private String description;
    
        public Item() {
        }
    
        public Item(Integer id, String description) {
            this.id = id;
            this.description = description;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
    }
    

    JSP sn-p

    <%
    HashMap<Integer, String> myMap = new HashMap<Integer, String>();
    myMap.put(new Integer(1), "One");
    myMap.put(new Integer(2), "Two");
    myMap.put(new Integer(3), "Three");
    request.setAttribute("myMap", myMap);
    
    List<com.me.Item> list=new ArrayList<com.me.Item>();
    list.add(new com.me.Item(1,"A - Desc"));
    list.add(new com.me.Item(2,"B - Desc"));
    list.add(new com.me.Item(3,"C - Desc"));
    request.setAttribute("list", list);
    %>
    
    <c:forEach items="${list}" var="item" varStatus="status">
      <c:out value="${item.description}"/>
      <c:out value="${myMap[item.id]}"/>
    </c:forEach>
    

    【讨论】:

      【解决方案3】:

      您可以将键值放在Java 一侧的映射中,并在JSP 页面上使用JSTL 访问相同,如下所示:

      Java 1.7 之前的版本:

      Map<String, String> map = new HashMap<String, String>();
      map.put("key","value");
      

      Java 1.7 及以上版本:

      Map<String, String> map = new HashMap<>();
      map.put("key","value");
      

      JSP 片段:

      <c:out value="${map['key']}"/>
      

      【讨论】:

        猜你喜欢
        • 2014-01-11
        • 2012-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-19
        • 1970-01-01
        • 2013-06-04
        • 1970-01-01
        相关资源
        最近更新 更多