简体   繁体   中英

How to get a value from hashmap within JSTL

I have seen a lot of questions like this, but not exactly. The difference is this is a foreign key issue. There is a collecton of widgets, foo, that has a typeId. Then there is a hashmap of types that contain both the typeId and typeName. When iterating over the collection of widgets, we want to to display the typeName based on the widget's typeId:

Java

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

List<Foo> fooList = generateFooList();

where Foo has a method String getTypeId() that returns the value of "1", "2", or "3" along with with a String getName().

JSTL

<table border="1">
    <tr><th>Key</th><th>value</th><th>Key Class</th></tr>
    <c:forEach var="foo" items="${fooList}" varStatus="status">
        <tr>      
          <td>${foo.name}</td>
          <td>${foo.typeId}</td>
<!-- In the following four lines of code, the idea is to use the typeId 
     from the current foo to 'get' the name of the type from the typeMap.
     All the example I have seen are always iterating over the map itself, 
     which is NOT the case here. -->
          <td>${typeMap['foo.typeId']}</td>
          <td>${typeMap[foo.typeId]}</td>
          <td>${typeMap['foo.typeId'].value}</td>
          <td>${typeMap[foo.typeId].value}</td>
          <td>${typeMap['1']}}</td>
        </tr>
    </c:forEach>
</table>

The first 4 columns that use typeMap are always empty, the last one does display 'One'. I have even go so far as to set the typeId into this:

<c:set var="typeId" value="${foo.typeId}"/>

And replaced all the foo.typeId with simply typeId, and I get the same effect. In this case I can change the map, I cannot change the foo. The foo's ID is a String, which cannot be changed to a Long. I have tried making the hashmap's key a Long and that does not have any effect, either. Any thoughts?

I really think that the fragment

<td>${typeMap['foo.typeId'].value}</td>

Should work.

Since it didn't. Try this:

<td>${typeMap[\'foo.typeId\'].value}</td>

As last resource, you could iterate both the list and the hashmap. And compare the "keys" of the hashmap with the list position. Then you only print the line when they are equal.

I know it's not the best, just a workaround.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM