Access a hash map value by a variable in JSP

I have a hashmap that fits in a request:

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

In JSP, I have a foreach loop

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

but ${myMap[item.id]}does not work. How can I access the hashmap value using a variable item.id?

+5
source share
3 answers

In EL, numbers are counted Long. Change Mapto Map<Long, String>and it will work.

+4
source

I think the id beans attribute is not a wrapper object ( Integer id;). See the Map document page .

Text from 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

<%
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

You can put the key value in the card on the side Javaand access the same using the page JSTLon JSP, as shown below:

Previous java 1.7:

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

Java 1.7 and later:

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

JSP Snippet:

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

All Articles