通过 JSTL 中的字符串键访问 TreeMap 条目
这与其他一些问题非常相似,但没有其他人使用字符串键。那么我们开始吧。
我有一个 TreeMap,其中包含一组类别名称,以类别 ID 为键。 ID 是一个数字(作为字符串)。
我使用值构建 TreeMap,然后将其公开到页面,如下所示:
<%
Map categories = new TreeMap();
...
String categoryId = ...;
String categoryName = ...;
categories.put(categoryId, categoryName);
...
pageContext.setAttribute("categories", categories);
%>
随后,我迭代一系列已分配给类别的项目。每个项目都有一个 .categories 集合,其中包含已分配给该项目的类别的 ID。我想显示名称,所以我做了这样的事情:
<c:forEach items="${item.categories}" var="catId">
${categories[“${catId}”}
</c:forEach>
不幸的是,这不会发出任何东西。 ${categories["${catId}"].value}.
也不会。
但是,这是:
${categories["2"]}
当然,该行实际上并不是由项目数据驱动的。
我检查过,每个项目附加的 ID 实际上与类别 ID 相对应;这不是数据不匹配问题。
那么,当附加到项目的数据只有 ID 时,如何获取类别名称呢?
PS 我应该提一下,我根本不是 Java 程序员。 LAMP 更符合我的风格。所以修改类并不是一个真正的选择。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:抱歉,我读错了问题。
解开您的
catId
变量:应该是
应该可以修复它。
EDIT: Sorry, I misread the question.
Unwrap your
catId
variable:should be
That should fix it.