Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access hashmap value by variable in JSP

Tags:

hashmap

jsp

el

I have a hashmap, which is put to the 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 hashmap's value by item.id variable ?

like image 915
hsz Avatar asked Jan 25 '11 10:01

hsz


3 Answers

In EL, numbers are treated as Long. Change your Map to be a Map<Long, String> and it'll work.

like image 151
BalusC Avatar answered Nov 13 '22 01:11

BalusC


I think the id attribute of beans is not a wrapper object (Integer id;). Have a look at doc page of Map.

Text from JavaDoc

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on a such a map.

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 snippet

<%
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>
like image 39
KV Prajapati Avatar answered Nov 13 '22 00:11

KV Prajapati


You can put the key-value in a map on Java side and access the same using JSTL on JSP page as below:

Prior java 1.7:

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

Java 1.7 and above:

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

JSP Snippet:

<c:out value="${map['key']}"/>
like image 3
Arpit Aggarwal Avatar answered Nov 12 '22 23:11

Arpit Aggarwal