Rob Hruska
Rob Hruska

Reputation: 120286

Evaluate variable before passing to JSP Tag Handler

When trying to use a custom JSP tag library, I have a variable defined in JSP that I would like to be evaluated before being passed to the tag library. However, I cannot seem to get it to work. Here's a simplified version of my JSP:

<% int index = 8; %>

<foo:myTag myAttribute="something_<%= index %>"/>

The doStartTag() method of my TagHandler uses the pageContext's output stream to write based on the inputted attribute:

public int doStartTag() {
    ...
    out.println("Foo: " + this.myAttribute);
}

However, the output I see in my final markup is:

Foo: something_<%= index %>

instead of what I want:

Foo: something_8

My tag library definition for the attribute is:

<attribute>
    <name>myAttribute</name>
    <required>true</required>
</attribute>

I have tried to configure the attribute with rtexprvalue both true and false, but neither worked. Is there a way I can configure the attribute so that it's evaluated before being sent to the Handler? Or am I going about this totally wrong?

I'm relatively new to JSP tags, so I'm open to alternatives for solving this problem. Also, I realize that using scriptlets in JSP is frowned upon, but I'm working with some legacy code here so I'm kind of stuck with it for now.

Edit:

I have also tried:

<foo:myTag myAttribute="something_${index}"/>

which does not work either - it just outputs something_${index}.

Upvotes: 3

Views: 3908

Answers (3)

Amir Arad
Amir Arad

Reputation: 6754

To keep your JSP code clean and neat, avoid scripting when possible. I think this is the preferred way to do it:

<foo:myTag >
  <jsp:attribute name="myAttribute">
    something_${index}
  </jsp:attribute>
</foo:myTag >

if your tag also contains a body, you'll have to change it from

<foo:myTag myAttribute="<%= attribValue %>">
  body
</foo:myTag >

to

<foo:myTag >
  <jsp:attribute name="myAttribute">
    something_${index}
  </jsp:attribute>
  <jsp:body>
    body
  </jsp:body>
</foo:myTag >

Upvotes: 2

Luke Woodward
Luke Woodward

Reputation: 64959

I don't believe that you can use a <%= ... %> within an attribute in a custom tag, unless your <%= ... %> is the entire contents of the attribute value. Does the following work for you?

<% int index = 8; %>
<% String attribValue = "something_" + index; %>

<foo:myTag myAttribute="<%= attribValue %>"/>

EDIT: I believe the <% ... %> within the custom tag attribute can only contain a variable name. not any Java expression.

Upvotes: 6

anon
anon

Reputation:

<foo:myTag myAttribute="something_${index}"/>

Upvotes: 0

Related Questions