How can I pass an object to a JSP tag?

后端 未结 4 1078
隐瞒了意图╮
隐瞒了意图╮ 2021-02-11 19:18

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.

For example I would

相关标签:
4条回答
  • 2021-02-11 20:03
    <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.

    0 讨论(0)
  • 2021-02-11 20:05

    The original syntax was to reuse '<%= %>'

    So

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

    See this part of the Sun Tag Library Tutorial for an example

    0 讨论(0)
  • 2021-02-11 20:13

    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 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.

    0 讨论(0)
  • 2021-02-11 20:16

    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.

    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.

    0 讨论(0)
提交回复
热议问题