JSP:如何在嵌套Map中按键获取值?

时间:2016-02-12 05:36:38

标签: jsp

假设我有一个跟随地图,我想按键在嵌套地图中打印值:

Map<Integer, Map<String, someObject>> map = new HashMap<Integer, Map<String, someObject>>();

所以,我的方法如下:

<c:forEach var="item1" items="${map}" varStatus="idx1">
   <c:forEach var="item2" items="${item1.value}" varStatus="idx2">
       <td>${item2['A'].variableInSomeObject}</td>
       <td>${item2['B'].variableInSomeObject}</td>
   </c:forEach>
</c:forEach>

也试过

<c:out value = "${item2['A'].variableInSomeObject}"/> 

但它会导致错误。 请指导我错过的内容。

1 个答案:

答案 0 :(得分:0)

当您使用<c:forEach>迭代地图时,迭代中的每个项目都是Map.Entry的实例。每个项目都包含keyvalue。对于项Map<Integer, Map<String, SomeObject>>keyInteger的实例,valueMap<String, SomeObject>的实例。

假设您有以下地图和嵌套地图:

Map<Integer, Map<String, SomeObject>> outerMap = 
        new HashMap<Integer, Map<String, SomeObject>>();
Map<String, SomeObject> firstNestedMap = new HashMap<String, SomeObject>();
Map<String, SomeObject> secondNestedMap = new HashMap<String, SomeObject>();

还有一些对象:

public class SomeObject {

    public Integer getVariableInSomeObject() {
        return variableInSomeObject;
    }

    public void setVariableInSomeObject(Integer variableInSomeObject) {
        this.variableInSomeObject = variableInSomeObject;
    }

    private Integer variableInSomeObject;
}

您可以填写地图,例如,如下所示:

SomeObject firstSomeObject = new SomeObject();
firstSomeObject.setVariableInSomeObject(1);

SomeObject secondSomeObject = new SomeObject();
secondSomeObject.setVariableInSomeObject(2);

SomeObject thirdSomeObject = new SomeObject();
thirdSomeObject.setVariableInSomeObject(3);

SomeObject fourthSomeObject = new SomeObject();
fourthSomeObject.setVariableInSomeObject(4);

firstNestedMap.put("A", firstSomeObject);
firstNestedMap.put("B", secondSomeObject);

secondNestedMap.put("A", thirdSomeObject);
secondNestedMap.put("B", fourthSomeObject);

outerMap.put(1, firstNestedMap);
outerMap.put(2, secondNestedMap);

要迭代嵌套映射并获取值,请使用以下JSTL代码:

<table>
<c:forEach var="item1" items="${map}">
    <c:forEach var="item2" items="${item1.value}">
    <tr>
        <td><c:out value="${item2.value.variableInSomeObject}" /></td>
    </tr>
    </c:forEach>
</c:forEach>
</table>

因此,每次迭代的item1.value将返回嵌套映射的实例,即Map<String, SomeObject>item2将返回SomeObject的实例。表达式${item2.value.variableInSomeObject}将返回Integer字段的实例。

结果,你会得到:

enter image description here