【问题标题】:How can i access a HashMap with JSTL-EL in a jsp?如何在 jsp 中使用 JSTL-EL 访问 HashMap?
【发布时间】:2011-06-24 15:20:13
【问题描述】:

大家好 我在使用 EL 和 JSTL 将 HashMap 访问到我的 jsl 时遇到问题 我的 hashmap 在 servlet 中是这样的:

HashMap indexes=new HashMap();

然后假设我添加了类似的东西:

indexes.put(1,"Erik")

然后我将它添加到会话中:session.setAttribute("indexes",indexes)

如果我像这样访问哈希图,则来自 jsp

${sessionScope.indexes}

它显示了地图中的所有键值对,例如:

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

它不会工作

据我所知,这是许多教程中使用的方法,我不知道我在哪里失败 有什么建议吗?

【问题讨论】:

    标签: jsp servlets jstl el


    【解决方案1】:

    数字在 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
    

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 1970-01-01
      • 2011-04-04
      • 2016-11-23
      相关资源
      最近更新 更多