Java 如何将对象传递给 JSP 标记?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/75626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I pass an object to a JSP tag?
提问by Joe Bienkowski
I have a JSP page that contains a scriplet where I instantiate an object. I would like to pass that object to the JSP tag without using any cache.
我有一个 JSP 页面,其中包含一个脚本,我在其中实例化了一个对象。我想将该对象传递给 JSP 标记而不使用任何缓存。
For example I would like to accomplish this:
例如我想完成这个:
<%@ taglib prefix="wf" uri="JspCustomTag" %>
<%
Object myObject = new Object();
%>
<wf:my-tag obj=myObject />
I'm trying to avoid directly interacting with any of the caches (page, session, servletcontext), I would rather have my tag handle that.
我试图避免直接与任何缓存(页面、会话、servletcontext)交互,我宁愿让我的标签处理它。
回答by Brian Matthews
Use expression language:
使用表达语言:
<wf:my-tag obj="${myObject}" />
回答by Garth Gilmour
The original syntax was to reuse '<%= %>'
原始语法是重用 '<%= %>'
So
所以
<wf:my-tag obj="<%= myObject %>" />
See this part of the Sun Tag Library Tutorialfor an example
有关示例,请参阅Sun 标记库教程的这一部分
回答by Pavel Feldman
For me expression language works only if I make that variable accessible, by putting it for example in page context.
对我来说,表达式语言只有在我使该变量可访问时才有效,例如将它放在页面上下文中。
<% Object myObject = new Object();
pageContext.setAttribute("myObject", myObject);
%>
<wf:my-tag obj="${myObject}" />
Otherwise tas receives null.
否则 tas 接收空值。
And <wf:my-tag obj="<%= myObject %>" />
works with no additional effort. Also <%=%> gives jsp compile-time type validation, while El is validated only in runtime.
并<wf:my-tag obj="<%= myObject %>" />
没有额外的努力工作。另外 <%=%> 给出了 jsp 编译时类型验证,而 El 只在运行时进行验证。
回答by Adeel Ansari
<jsp:useBean id="myObject" class="java.lang.Object" scope="page" />
<wf:my-tag obj="${myObject}" />
Its not encouraged to use Scriptlets in JSP page. It kills the purpose of a template language.
不鼓励在 JSP 页面中使用 Scriptlets。它扼杀了模板语言的目的。
回答by dfrankow
A slightly different question that I looked for here: "How do you pass an object to a tag file?"
我在这里寻找的一个稍微不同的问题:“如何将对象传递给标记文件?”
Answer: Use the "type" attribute of the attribute directive:
答:使用attribute指令的“type”属性:
<%@ attribute name="field"
required="true"
type="com.mycompany.MyClass" %>
The type defaults to java.lang.String, so without it you'll get an error if you try to access object fields saying that it can't find the field from type String.
该类型默认为 java.lang.String,因此如果没有它,如果您尝试访问对象字段,说它无法从 String 类型中找到该字段,则会出现错误。
回答by Mike Clark
You can use "<%= %>" to get the object value directly in your tag :
您可以使用 "<%= %>" 直接在标签中获取对象值:
<wf:my-tag obj="<%= myObject %>"/>
and to get the value of any variable within that object you can get that using "obj.parameter" like:
并获取该对象中任何变量的值,您可以使用“obj.parameter”获取该值,例如:
<wf:my-tag obj="<%= myObject.variableName %>"/>