Access TreeMap entries by string key in JSTL
This is pretty similar to some other questions, but nobody else is working with string keys. So here we go.
I've got a TreeMap with a set of category names, keyed by category ID. The ID is a number (as a String).
I build up the TreeMap with values, then expose it to the page, like so:
<%
Map categories = new TreeMap();
...
String categoryId = ...;
String categoryName = ...;
categories.put(categoryId, categoryName);
...
pageContext.setAttribute("categories", categories);
%>
Later, I iterate开发者_Python百科 through a series of items which have been assigned to categories. Each item has a .categories collection which contains the IDs of the categories to which it has been assigned. I want to display the names, so I do something like this:
<c:forEach items="${item.categories}" var="catId">
${categories[“${catId}”}
</c:forEach>
Unfortunately, this doesn't emit anything. Nor does ${categories["${catId}"].value}.
However, this does:
${categories["2"]}
Of course, that line isn't actually driven by item data.
I've checked, and the IDs attached to each item do in fact correspond to category IDs; this isn't a data mismatch problem.
So, how do I get my hands on category names when the data attached to items has only IDs?
P.S. I should mention that I'm not a Java programmer -- at all. LAMP is more my style. So modifying classes isn't really an option.
EDIT: Sorry, I misread the question.
Unwrap your catId
variable:
${categories[“${catId}”}
should be
${categories[catId]}
That should fix it.
精彩评论