In Struts 1, I have used map-backed action form to get dynamic fields values.
public MyForm extends ActionForm {
private final Map values = new HashMap();
public void setValue(String key, Object value) {
values.put(key, value);
}
public Object getValue(String key) {
return values.get(key);
}
}
Below is the code I have used.
JSP
<form action="/SaveAction.do">
<input type="text" name="value(dynamicNames)" value="some value">
</form>
Action
public class SaveAction extends ActionSupport implements ModelDriven<MyForm> {
private MyForm myForm = new MyForm();
@Override
public MyForm getModel() {
return myForm;
}
public void setMyForm(MyForm myForm){
this.myForm = myForm;
}
public MyForm getMyForm(){
return myForm;
}
public String execute(){
MyForm formData = getMyForm();//Here I am getting empty object.
return "SUCCESS";
}
}
Form
public MyForm {
private final Map values = new HashMap();
public void setValue(String key, Object value) {
values.put(key, value);
}
public Object getValue(String key) {
return values.get(key);
}
}
How to achieve the same functionality in Struts 2 ?
You should map the fields of the form to the action like this
<s:textfield name="myForm.values['%{dynamicNames}']"/>
It doesn't clear what value is for dynamicNames
, actually it should be the key for the object pushed on the value stack while iterating the map and as soon as you running model driven the code will look like
<s:iterator value="values">
<s:textfield name="myForm.values['%{key}']"/>
</s:iterator>
OGNL will take care of the mapping such names and populate values of the fileds in the form and in the action when you submit the form.
In addition if you need to place the values entered by user to another object say myForm2
then you could use value attribute value="%{value}"
of the textfield to populate the form from the first model.
See the reference guide how to use model driven interface and model driven interceptor. Also there's a reference to get you know how objects from the form converted by type to the action objects.