简体   繁体   English

如何将对象传递给JSP标记?

[英]How can I pass an object to a JSP tag?

I have a JSP page that contains a scriplet where I instantiate an object. 我有一个JSP页面,其中包含一个scriplet,我在其中实例化一个对象。 I would like to pass that object to the JSP tag without using any cache. 我想将该对象传递给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)交互,我宁愿让我的标签处理。

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: 答案:使用属性指令的“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类型中找到该字段,则会出现错误。

<jsp:useBean id="myObject" class="java.lang.Object" scope="page" />
<wf:my-tag obj="${myObject}" />

Its not encouraged to use Scriptlets in JSP page. 不鼓励在JSP页面中使用Scriptlets。 It kills the purpose of a template language. 它杀死了模板语言的目的。

The original syntax was to reuse '<%= %>' 原始语法是重用'<%=%>'

So 所以

<wf:my-tag obj="<%= myObject %>" />

See this part of the Sun Tag Library Tutorial for an example 有关示例,请参阅Sun Tag Library Tutorial的这一部分

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收到null。

And <wf:my-tag obj="<%= myObject %>" /> works with no additional effort. 并且<wf:my-tag obj="<%= myObject %>" />无需额外工作。 Also <%=%> gives jsp compile-time type validation, while El is validated only in runtime. 此外,<%=%>提供jsp编译时类型验证,而El仅在运行时验证。

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 %>"/>

Use expression language: 使用表达式语言:

<wf:my-tag obj="${myObject}" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM