2011-02-10 74 views
1

大家好 我有訪問一個HashMap中到使用EL和JSTL 我的HashMap的是,像這樣在servlet我JSL一個問題:如何在jsp中使用JSTL-EL訪問HashMap?

HashMap indexes=new HashMap(); 

然後讓想我添加的財產以後,如:

indexes.put(1,"Erik") 

然後我把它添加到會話:session.setAttribute("indexes",indexes)

從JSP,如果我像這樣訪問

HashMap中
${sessionScope.indexes} 

它顯示在地圖中的所有鍵值對,但像這樣的例子:

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

它不會工作

,據我可以看到這是在很多使用的ethod教程我不知道我在哪裏失敗 任何建議?

回答

3

在EL中將數字視爲Long。你的情況:

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

和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 

因此,要麼你可以讓你的地圖的關鍵是長或字符串使用。

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

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

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

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

嗨Jigar THX的意見,但它不工作。 – JBoy 2011-02-10 06:28:56