在 EL 中创建列表
假设我有一个采用字符串列表的自定义标记:
<%@ attribute name="thelist" type="java.util.List<java.lang.String>"
required="true" %>
如何在调用该标记的 jsp 中创建此属性?我可以使用脚本,
<tags:list thelist='<%= java.util.Arrays.asList("blah","blah2") %>' />
但有什么方法可以使用表达式语言来做到这一点,因为这似乎是首选?
Suppose I have a custom tag that takes a List of Strings:
<%@ attribute name="thelist" type="java.util.List<java.lang.String>"
required="true" %>
How can I create this attribute in the jsp that calls the tag? I could use a scriptlet
<tags:list thelist='<%= java.util.Arrays.asList("blah","blah2") %>' />
but is there any way to do this using Expression Language, since that seems to be preferred?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您只想创建列表,那么您可以使用
[][1]
在所需范围内创建对象:这有效,因为 ArrayList 没有args 构造函数。但是,该列表中不会包含任何内容。而且,据我所知,EL 和 JSTL 都没有提供向集合添加项目的内置机制——它们都专注于只读访问。我想您可以定义 EL 函数映射 启用
add()
方法。不过,我认为最好不要试图强迫 JSP 做它不想做的事情。在这种情况下,这意味着您应该用 Java 编写实际的标记处理程序,而不是使用 JSP 标记文件。
If all you want to do is create the list, then you can use
[<jsp:useBean>][1]
to create the object in the desired scope:This works because ArrayList has a no-args constructor. However, the list won't have anything in it. And, as far as I know, neither EL nor JSTL provide a built-in mechanism for adding items to a collection -- they're both focused on read-only access. I suppose that you could define an EL function mapping to enable the
add()
method.However, I think that you're better off not trying to force JSP to do something that it doesn't want to do. In this case, that means that rather than use a JSP tagfile, you should write an actual tag handler in Java.
从 EL 3 开始,您只需执行
#{['blah','blah2']}
即可创建列表。Since EL 3 you can simply do
#{['blah','blah2']}
to create a list.正如 kdgregory 所说,您可以使用 自定义标记库函数,尽管它不会很漂亮。例如,这样的事情:
您只是遇到了过去所谓的 最简单的可能表达语言。
通过其他机制(例如 bean)来完成此操作会更容易。
As kdgregory says, you could do this with custom tag library functions, though it won't be pretty. For example, something like this:
You are merely running into the limitations of what used to be called the Simplest Possible Expression Language.
It would be easier to do this via some other mechanism, like a bean.
如果您想避免 scriptlet 或丑陋的 EL 函数,您可以使用自己的构建器并欺骗 EL 解释器:
查看此处的示例: https://gist.github.com/4581179
If you want to avoid scriptlet or ugly EL functions, you could use you own builder and fool the EL interpreter:
Check the example here: https://gist.github.com/4581179