Alternative Actionform alternative in Struts 2

In Struts 1, I used a map-enabled form to get dynamic field 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 used.

Jsp

 <form action="/SaveAction.do"> <input type="text" name="value(dynamicNames)" value="some value"> </form> 

Act

 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"; } } 

The 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?

+4
source share
2 answers

You must map the form fields to an action like this

 <s:textfield name="myForm.values['%{dynamicNames}']"/> 

It is unclear what the value is for dynamicNames , in fact it should be the key for the object pressed on the stack of values, iterating the map, and as soon as you run the model, the code will look like

 <s:iterator value="values"> <s:textfield name="myForm.values['%{key}']"/> </s:iterator> 

OGNL will take care of displaying such names and fill in the field values ​​in the form and in action when submitting the form.

In addition, if you need to put the values ​​entered by the user to another object, say myForm2 , then you can use the value value="%{value}" attribute of the text field to fill out the form from the first model.

See the reference guide on how to use the model-driven interface and model interceptor drive . There is also a link to find out how objects from a form are converted by type into action objects.

+2
source

You can put your map directly into the action class, and in JSP use the Struts2 tags to send / receive values.

Act

 public class SaveAction extends ActionSupport { private Map<String, Object> map; public String execute(){ // do something with map return SUCCESS; } // getter/setter for map } 

Jsp

 <s:form action="saveAction"> <s:textfield name="map['somekey']" /> <s:submit /> </s:form> 
+3
source

Source: https://habr.com/ru/post/1491858/


All Articles