Map-backed Actionform alternative in Struts 2

别来无恙 提交于 2019-12-18 13:37:46

问题


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 ?


回答1:


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.




回答2:


You can put your map directly to action class and in JSP use Struts2 tags to submit/get values.

Action

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>


来源:https://stackoverflow.com/questions/17698456/map-backed-actionform-alternative-in-struts-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!