大家好 我有一个问题,使用EL和JSTL访问我的jsl HashMap 我的hashmap就像在servlet中一样:
HashMap indexes=new HashMap();
然后让我假设我添加如下内容:
indexes.put(1,"Erik")
然后我将其添加到会话中:session.setAttribute("indexes",indexes)
${sessionScope.indexes}
它显示了地图中的所有键值对,但是像这样:
${sessionScope.indexes[1]} or ${sessionScope.indexes['1']}
它不会工作
据我所知,这是许多教程中使用的方法,我不知道我在哪里失败 有什么建议吗?
答案 0 :(得分: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
因此,您可以使您的地图密钥为Long或String。
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