views:

1765

answers:

6

I have a JSP page that contains a scriplet where i instantiate an object. I would like to pass that object into the JSP tag without using any cache.

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.

A: 

Use expression language:

    <wf:my-tag obj="${myObject}" />
bmatthews68
We need to add that in some context, prior using it.
Adeel Ansari
+2  A: 

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

So

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

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

Garth Gilmour
I remember that and man is it ugly! +1
Yar
+1  A: 

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.

Pavel Feldman
Use JSP compile, you will get the error on compile time.
Adeel Ansari
+4  A: 
<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.

Adeel Ansari
+3  A: 

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.

dfrankow
A: 

It is worth looking at this link...

http://www.coderanch.com/t/293634/JSP/java/Passing-ArrayList-JSP-custom-Tag

Sudhakar R