Struts 2 dynamic variables
Asked Answered
B

2

11

I'm trying to create a dynamic variable in Struts2 using set tag

<s:set var="myNum" value="numConst" />
<s:set var="number" value="%{getText('@xxx.CommonConstant@'+#myNum)}" />

numConst will return a dynamic value that retrieved from database. For example, if the value is NINE then number should be @xxx.CommonConstant@NINE

I have set the value in my java class so that @xxx.CommonConstant@NINE will return 9.

So far, the value can be displayed with no problem in text tag if I use

<s:text name="%{getText(#number)}" /> 

It will return 9 but it displayed incorrectly when I tried using property tag

<s:property value="%{getText(#number)}" /> 
<s:property value="%{#number}" />
<s:property value="#number" />
<s:property value="%{getText('%{getText(#number)}')}" />

Which all of the above examples will give me the value as @xxx.CommonConstant@NINE. The reason I try to get the value from property tag is because I want to copy the correct way on how to display the value so I can use them in if tag like below examples:

<s:if test="#number == 9">
   do something
</s:if>

or

<s:if test="%{getText(#number)} == 9">
   do something
</s:if>

CommonConstant:

package xxx;

public abstract class CommonConstant {
    public static final int NINE = 9;
    public static final int NINEONE = 91;
    public static final double ADMIN_PGM = 1.4;
    // ... omitted ... 
}

Can anybody help me?

Bleeder answered 23/5, 2013 at 11:9 Comment(5)
And what is CommonConstant? Is it enum? Could you show the code.Guenon
getText method is for getting localized text. Why are you using it like that?Guenon
package xxx; public abstract class CommonConstant { public static final int NINE = 9; public static final int NINEONE = 91; public static final double ADMIN_PGM = 1.4; ... omitted ... }Bleeder
yeah @AleksandrM I guess because I get used to use localization until I tried it out.. but <s:text name="%{#number}" /> also will give me the expected value but not with <s:property value="%{#number}" />Bleeder
Yuck. If you actually need this then change how it works on the server side; make a real map. Also more testable that way.Rankin
G
11

It seems like a workaround but you can use attr to evaluate string.

<s:set var="myNum" value="numConst" />
<s:set var="number" value="'@xxx.CommonConstant@'+#myNum" />

<s:property value="#attr[#number]"/>

<s:if test="#attr[#number] == 9">
  do something
</s:if>
Guenon answered 23/5, 2013 at 12:13 Comment(0)
L
7

You can use parenthesesized expression to evaluate result of the expression.

<s:if test="#number(0) == 9">
  <s:property value="%{#number(0)}" />
</s:if>

Look at the Expression Evaluation of the OGNL language guide.

Laryngeal answered 23/5, 2013 at 14:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.