JBoy
JBoy

Reputation: 5755

How can i access a HashMap with JSTL-EL in a jsp?

Hi all I have a problem with accessing an HashMap into my jsl using EL and JSTL my hashmap is like so in the servlet:

HashMap indexes=new HashMap();

then lets suppose i add somthing like:

indexes.put(1,"Erik")

then i add it to the session:session.setAttribute("indexes",indexes)

from the jsp if i access the hashmap like this

${sessionScope.indexes}

it shows all key-value pair in the map, but like this for example:

${sessionScope.indexes[1]} or ${sessionScope.indexes['1']}

it wont work

as far as i can see this is the ethod used in many tutorials i dont know where i'm failing any suggestion?

Upvotes: 1

Views: 4784

Answers (1)

Jigar Joshi
Jigar Joshi

Reputation: 240996

Numbers are treated as Long in EL. In your case:

HashMap indexes = new HashMap();
indexes.put(1, "Erik"); // here it autobox 1 to Integer

and on jsp

${sessionScope.indexes[1]} // will search for Long 1 in map as key so it will return null
${sessionScope.indexes['1']} // will search for String 1 in map as key so it will return null

So either you can make your map key is a Long or String to use .

Map<Long, String> indexes = new HashMap<Long, String>();
indexes.put(1L, "Erik"); // here it autobox 1 to Long

and

${sessionScope.indexes[1]} // will look for Long 1 in map as key

or

Map<String, String> indexes = new HashMap<String, String>();
indexes.put("1", "Erik");

and

${sessionScope.indexes['1']} // will look for String 1 in map as key

Upvotes: 3

Related Questions