Reputation: 45
This is my struts.xml
class:
<action name="{param1}/{param2}/{param3}"
class="myactionclass"
method="execute">
<result name="success">/success.jsp</result>
</action>
So in my action class, I have to create three String
objects String param1, param2, param3
(and add getter and setter methods) to get the param
values. What I want to do is, instead of creating 3 different String objects, create a single String array and store the param
values into the String array using the setter.
How do I achieve this in my action class ?
Upvotes: 1
Views: 875
Reputation: 24396
You need to tell which parameter will go to which index in the array.
<action name="{param[0]}/{param[1]}/{param[2]}" class="myactionclass">
<result name="success">/success.jsp</result>
</action>
Action (using array):
private String[] param = new String[3];
// getter and setter
Instead of array you can use List
, then there is no need to initialize it in the action.
Action (using List
):
private List<String> param;
// getter and setter
Map
is also an option.
Action (using Map
):
private Map<String, String> param;
// getter and setter
struts.xml (using Map
in action):
<action name="{param['p1']}/{param['p2']}/{param['p3']}" class="myactionclass">
<result name="success">/success.jsp</result>
</action>
Upvotes: 1
Reputation: 1614
Populating an array in Struts2 using parameters in query-string is pretty easy.
In your Action declare the array with corresponding setter
private String[] fruits;
public void setFruits(String[] fruits) {
this.fruits = fruits;
}
This request will populate your fruits
array
/myactionuri?fruits=apple&fruits=banana&fruits=peach
But with static parameters this mechanism doesn't seem to work in the same way.
I found this solution, maybe not as elegant, but it works.
In your struts.xml
:
<!-- warning: this pattern matches all requests with 3 tokens separated by slashes -->
<action name="*/*/*" class="com.xxx.MyAction" >
<param name="f1">{1}</param>
<param name="f2">{2}</param>
<param name="f3">{3}</param>
</action>
And in your Action:
private String[] fruits = new String[3]; //need to be initiated
public void setF1(String f1) {
this.fruits[0] = f1;
}
public void setF2(String f2) {
this.fruits[1] = f2;
}
public void setF3(String f3) {
this.fruits[2] = f3;
}
Hope this will help you.
Upvotes: 3