Struts 2 中的 Map-backed Actionform 替代方案 [英] Map-backed Actionform alternative in Struts 2

查看:20
本文介绍了Struts 2 中的 Map-backed Actionform 替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Struts 1 中,我使用了 map-backed action form 获取动态字段值.

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

下面是我使用的代码.

JSP

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

动作

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

表格

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

如何在 Struts 2 中实现相同的功能?

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}']"/> 

不清楚 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 将负责映射此类名称并在您提交表单时填充表单和操作中的字段值.

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.

此外,如果您需要将用户输入的值放到另一个对象中,比如 myForm2,那么您可以使用值属性 value=%{value}"用于从第一个模型填充表单的文本字段.

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.

这篇关于Struts 2 中的 Map-backed Actionform 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆