且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Struts 2:从具有模型驱动架构的表单更新对象列表

更新时间:2023-11-29 14:59:52

好的 - 这是一个非常基本的列表索引工作示例.主要的变化是将模型的创建从 getModel() 移动到 prepare().这是因为 getModel() 会为您需要设置列表的每个值调用 - 因此每次覆盖之前的更改时您最终都会重新创建模型.

Ok - here is a very basic working example of list indexing. The main change is to move the creation of the model from getModel() to prepare(). This is because getModel() is called for every value you need to set the list - so you end up re-creating your model each time overwriting the previous change.

package com.blackbox.x.actions;

import java.util.ArrayList;
import java.util.List;

import com.blackbox.x.actions.ListDemo.ValuePair;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class ListDemo extends ActionSupport implements ModelDriven<List<ValuePair>>, Preparable {


private List<ValuePair> values;

@Override
public List<ValuePair> getModel() {

    return values;

}

public String execute() {

    for (ValuePair value: values) {
        System.out.println(value.getValue1() + ":" + value.getValue2());
    }

    return SUCCESS;
}


public void  prepare() {
    values = new ArrayList<ValuePair>();
    values.add(new ValuePair("chalk","cheese"));
    values.add(new ValuePair("orange","apple"));
}


public class ValuePair {

    private String value1;
    private String value2;

    public ValuePair(String value1, String value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    public String getValue1() {
        return value1;
    }
    public void setValue1(String value1) {
        this.value1 = value1;
    }
    public String getValue2() {
        return value2;
    }
    public void setValue2(String value2) {
        this.value2 = value2;
    }
}
}

和对应的jsp

<%@ taglib prefix="s" uri="/struts-tags" %>    
<html>
<head>


</head>
<body>


<s:form action="list-demo" theme="simple">
<table>
<s:iterator value="model" status="rowStatus">
<tr>
<td><s:textfield name="model[%{#rowStatus.index}].value1" value="%{model[#rowStatus.index].value1}"/></td>
<td><s:textfield name="model[%{#rowStatus.index}].value2" value="%{model[#rowStatus.index].value2}"/></td>
</tr>
</s:iterator>
</table>
<s:submit/>
</s:form>
</body>
</html>