Glen Mazza Glen Mazza - 5 months ago 42
Java Question

Using Struts2 s:set variables with getText()

Using Struts2 with JSPs. The following code works fine:

<s:if test="foo == bar">
<s:set var="keyValue">message.string1</s:set>
</s:if>
<s:else>
<s:set var="keyValue">message.string2</s:set>
</s:else>

<s:text name="%{keyValue}"/>


i.e., based on the value of
keyValue
,
message.string1
or
message.string2
is looked up from the resource file and properly output to the resulting HTML page.

However, as explained at the bottom of the Struts tag documentation, for i18n in attribute values I can't use the Struts text tag, instead I have to use
getText('...')
:

<s:submit value="getText('message.string1')" ../>


Problem is, I can't get
%{keyValue}
resolved in the above
getText()
call, whatever syntax I try:
getText('%{keyValue}')
,
getText(%{keyValue})
,
getText(keyValue)
,
getText('keyValue')
it ends up getting evaluated as null. Is this a syntax error on my part or it simply can't be done? If I have to, I know I can go back to using
<s:if>
and
<s:else>
with a submit tag under each:

<s:if test="foo == bar">
<s:submit value="getText('message.string1')" ../>
</s:if>
<s:else>
<s:submit value="getText('message.string2')" ../>
</s:else>


...but I'd like to avoid the duplication if possible.

Answer

Although plain keyValue will work in most cases, it is always better to prefix var values of the <s:set> tag with #. You should use only one pair of %{} around the whole expression.

<s:submit value="%{getText(#keyValue)}" />
Comments