86

我有一个由整数键控的地图。使用 EL,如何通过键访问值?

Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

我认为这会起作用,但它不起作用(地图已经在请求的属性中):

<c:out value="${map[1]}"/>

跟进:我找到了问题所在。显然${name[1]}用数字作为一个地图查找Long。当我更改HashMapTreeMap并收到错误时,我发现了这一点:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

如果我将地图更改为:

Map<Long, String> map = new HashMap<Long, String>();
map.put(1L, "One");

然后${name[1]}返回“一”。那是怎么回事?为什么<c:out>将数字视为长。对我来说似乎违反直觉(因为 int 比 long 更常用)。

所以我的新问题是,是否有 EL 表示法可以通过Integer值访问地图?

4

5 回答 5

118

初步答案(EL 2.1,2009 年 5 月)

正如这个java论坛线程中提到的:

基本上自动装箱将一个整数对象放入地图中。IE:

map.put(new Integer(0), "myValue")

EL(表达式语言)将 0 评估为 Long 并因此寻找 Long 作为映射中的键。即它评估:

map.get(new Long(0))

由于 aLong永远不等于Integer对象,因此它不会在映射中找到条目。
简而言之就是这样。


自 2009 年 5 月以来的更新 (EL 2.2)

2009 年 12 月引入了 EL 2.2 和 JSP 2.2/Java EE 6,与EL 2.1 相比有一些不同
似乎(“ EL Expression parsing integer as long ”):

您可以在 EL 2.2intValue中的对象 self 上Long调用该方法:

<c:out value="${map[(1).intValue()]}"/>

这可能是一个很好的解决方法(在下面的Tobias Liefke回答中也提到过)


原答案:

EL 使用以下包装器:

Terms                  Description               Type
null                   null value.               -
123                    int value.                java.lang.Long
123.00                 real value.               java.lang.Double
"string" ou 'string'   string.                   java.lang.String
true or false          boolean.                  java.lang.Boolean

JSP 页面演示了这一点:

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

 <%@ page import="java.util.*" %>

 <h2> Server Info</h2>
Server info = <%= application.getServerInfo() %> <br>
Servlet engine version = <%=  application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
Java version = <%= System.getProperty("java.vm.version") %><br>
<%
  Map map = new LinkedHashMap();
  map.put("2", "String(2)");
  map.put(new Integer(2), "Integer(2)");
  map.put(new Long(2), "Long(2)");
  map.put(42, "AutoBoxedNumber");

  pageContext.setAttribute("myMap", map);  
  Integer lifeInteger = new Integer(42);
  Long lifeLong = new Long(42);  
%>
  <h3>Looking up map in JSTL - integer vs long </h3>

  This page demonstrates how JSTL maps interact with different types used for keys in a map.
  Specifically the issue relates to autoboxing by java using map.put(1, "MyValue") and attempting to display it as ${myMap[1]}
  The map "myMap" consists of four entries with different keys: A String, an Integer, a Long and an entry put there by AutoBoxing Java 5 feature.       

  <table border="1">
    <tr><th>Key</th><th>value</th><th>Key Class</th></tr>
    <c:forEach var="entry" items="${myMap}" varStatus="status">
    <tr>      
      <td>${entry.key}</td>
      <td>${entry.value}</td>
      <td>${entry.key.class}</td>
    </tr>
    </c:forEach>
</table>

    <h4> Accessing the map</h4>    
    Evaluating: ${"${myMap['2']}"} = <c:out value="${myMap['2']}"/><br>
    Evaluating: ${"${myMap[2]}"}   = <c:out value="${myMap[2]}"/><br>    
    Evaluating: ${"${myMap[42]}"}   = <c:out value="${myMap[42]}"/><br>    

    <p>
    As you can see, the EL Expression for the literal number retrieves the value against the java.lang.Long entry in the map.
    Attempting to access the entry created by autoboxing fails because a Long is never equal to an Integer
    <p>

    lifeInteger = <%= lifeInteger %><br/>
    lifeLong = <%= lifeLong %><br/>
    lifeInteger.equals(lifeLong) : <%= lifeInteger.equals(lifeLong) %> <br>
于 2009-05-29T05:44:08.417 回答
11

除了上述注释之外,另一个有用的提示是当您在某个变量(例如请求参数)中包含一个字符串值时。在这种情况下,将其传入也会导致 JSTL 将“1”的值作为字符串键入,因此在 Map hashmap 中找不到匹配项。

解决这个问题的一种方法是做这样的事情。

<c:set var="longKey" value="${param.selectedIndex + 0}"/>

这现在将被视为一个 Long 对象,然后当它包含在地图 Map 或其他内容中时有机会匹配一个对象。

然后,像往常一样继续

${map[longKey]}
于 2011-03-29T14:44:03.567 回答
10

如果将数字放入“(”“)”,则可以使用 Long 中的所有功能。这样,您可以将 long 转换为 int:

<c:out value="${map[(1).intValue()]}"/>
于 2014-12-17T19:34:06.057 回答
3

根据上面的帖子,我尝试了这个并且效果很好我想使用 Map B 的值作为 Map A 的键:

<c:if test="${not empty activityCodeMap and not empty activityDescMap}">
<c:forEach var="valueMap" items="${auditMap}">
<tr>
<td class="activity_white"><c:out value="${activityCodeMap[valueMap.value.activityCode]}"/></td>
<td class="activity_white"><c:out value="${activityDescMap[valueMap.value.activityDescCode]}"/></td>
<td class="activity_white">${valueMap.value.dateTime}</td>
</tr>
</c:forEach>
</c:if>
于 2012-01-24T00:53:31.290 回答
3

如果您碰巧有一个无法更改的MapwithInteger键,您可以编写一个自定义 EL 函数将 a 转换LongInteger. 这将允许您执行以下操作:

<c:out value="${map[myLib:longToInteger(1)]}"/>
于 2012-09-28T08:27:20.993 回答