Passing variable number of parameters from form in to action in struts 2

3.4k views Asked by At

I am using struts2 in my application and have a form in a jsp which is submitted to a action class.

The number of input fields in the form can vary at runtime and hence the action class can not have fixed setter and getter for the parameters. I am trying to capture these variable number of inputs in a single action class. I want to know if its possible via Struts 2 and if it is how can i do it ? I am aware of the input field names in the form (input field names populated via iterator in the jsp form).

Note: 1) I am aware of the way to capture the form values (parameters) in the action class via the appropriate getter and setter for all form values in the action class. 2) I have gone through the model driven action as described in struts 2 http://struts.apache.org/2.3.1/docs/model-driven.html

I could not get any solution on searching and any help is appreciated.

Form population code:

<s:form action="/reports/getReport.action" cssClass="table_with_padding">
   <s:iterator value="reportParamsList.items" id="paramList_item">
       <tr><td><s:property value="#paramList_item.paramdesc" /></td><TD><s:textfield name="#paramList_item.paramname" /></TD></tr>
    </s:iterator>
    <s:submit theme="ajax" loadingText="%{getResource('SiteWide.Loading.Text')}" targets="app_area" type="button" align="left" cssClass="app_form_button" value="Submit" />
</s:form>
3

There are 3 answers

0
Anupam On

Use same name attribute for all textfields and a corresponding hidden field to identify it

<s:iterator value="reportParamsList.items" id="paramList_item">
       <tr>
           <td>
               <s:property value="#paramList_item.paramdesc" />
           </td>
           <td>
                <s:textfield name="element" />
                <s:hidden name="myValue" value="#paramList_item.paramname" />
           </td>
       </tr>
</s:iterator>

Then in your action class declare these variables and their getter/setter

private List<String> element;
private List<String> myValue;

Now you can iterate over myValue list and get its corresponding textfield's value

Iterator<String> it = myValue.iterator();
int index = 0;
while(it.hasNext()){
 System.out.println("hidden field's value="+it.next());
 System.out.println("textfield's value="+element.get(index));
 index++;
}
1
Jigar Joshi On

Just take a List in form and bind data with list on view

0
mprabhat On

For variable parameters I don't think Struts2 has any built in feature, instead before you submit your form you save the value of all variable parameters in some field as say delimited String and then send it across to your Action.

In your Action you can then parse the delimited String and get the result out.

You can use s:hidden to hold your delimited value