JSP/JSTL:将集合传递给自定义标记
我正在尝试实现一个自定义 JSP 标记,该标记接受对象的 Collection
作为属性,并将它们输出为 JSON 格式的数组(Collection
中的每个对象都提供一个getJsonString()
方法,返回该对象的 JSON 格式表示形式)。我的标签是这样实现的:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ attribute name="objects" required="true" rtexprvalue="true" %>
<c:set var="output" value="" />
<c:forEach var="obj" items="${objects}">
<c:if test="${! empty showComma}">
<c:set var="output" value="${output}, " />
</c:if>
<c:set var="output" value="${output}${obj.jsonString}" />
<c:set var="showComma" value="yes" />
</c:forEach>
[${output}]
...并且我希望能够通过执行以下操作来使用它:
<myTaglib:jsonArray objects="${myCollection}" />
但是,当我尝试使用该标签时,我得到一个堆栈跟踪:
javax.el.PropertyNotFoundException: Property 'jsonString' not found on type java.lang.String
所以它抱怨 ${obj.jsonString}
表达式,但我绝对不会传递字符串的 Collection
。此外,如果我将其更改为 ${obj}
我会看到输出的正确对象类型,并且如果我将自定义标记的代码复制/粘贴到我想要使用它的 JSP 中,它工作正常,所以我真的不确定这里发生了什么。
我认为将 Collection
传递到自定义标记中的方式存在一些问题,但我无法弄清楚它是什么。有什么想法吗?
I'm trying to implement a custom JSP tag that accepts as an attribute a Collection
of objects and outputs them as a JSON-formatted array (each object in the Collection
provides a getJsonString()
method that returns a JSON-formatted representation of that object). I have my tag implemented as such:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ attribute name="objects" required="true" rtexprvalue="true" %>
<c:set var="output" value="" />
<c:forEach var="obj" items="${objects}">
<c:if test="${! empty showComma}">
<c:set var="output" value="${output}, " />
</c:if>
<c:set var="output" value="${output}${obj.jsonString}" />
<c:set var="showComma" value="yes" />
</c:forEach>
[${output}]
...and I want to be able to use it by doing something like:
<myTaglib:jsonArray objects="${myCollection}" />
When I try to use the tag, however, I get a stack trace saying:
javax.el.PropertyNotFoundException: Property 'jsonString' not found on type java.lang.String
So it's complaining about the ${obj.jsonString}
expression, but I'm definitely not passing a Collection
of strings. Moreover, if I change it to ${obj}
I see the correct object types being output, and if I copy/paste the code for my custom tag into the JSP where I want to use it, it works correctly, so I'm really not sure what's going on here.
I assume there is some problem with how I'm passing the Collection
into the custom tag, but I can't work out what it is. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了解决方案,我需要将
type="java.util.Collection"
添加到属性声明中,如下所示:...我本以为 Java 会足够聪明来解决这个问题它自己的,但显然不是。
I found the solution, I needed to add
type="java.util.Collection"
to the attribute declaration, as in:...I would have thought Java would be smart enough to figure that out on its own, but apparently not.