struts2迭代器中填充的列表值列表

时间:2011-10-25 23:25:49

标签: list struts2

对于我的情况,这有点棘手。我只是在person对象中有另一个列表,它被称为状态。如下所示:

public class People {
    private int id;
    private String name;
    private List<State> states;
    // Plus setters/getters
}

public class State {
    private int id;
private String stateAbbr;
private String stateName;
public State (String stateAbbr, String stateName) {
this.stateAbbr = stateAbbr;
this.stateName = stateName;
}
   // Plus setters/getters
}

动作类:

public class PersonAction extends ActionSupport {
private List<People> peopleList;

public List<People> getPeopleList() {
    return peopleList;
}

public void setPeopleList(List<People> peopleList) {
    this.peopleList = peopleList;
}

//Initial Load method
@Override
public String execute() {
    peopleList = new ArrayList<People>();

    int alpha = 65;
    for(int i = 0; i < 3 ; i++) {
        People people = new People();
        people.setId(i);
        people.setName(String.valueOf((char)alpha++));
        peopleList.add(people);
    }

    for (People people : peopleList){
        State state = new State("BC", "BritishColumbia");
        List<State> states = new ArrayList<State>();
        states.add(state);
        state = new State("AC", "AppleColumbia");
        states.add(state);
        people.setStates(states);
    }
    return SUCCESS;
}

//Function that handles the form submit
public String updatePerson() {
    for(People people : peopleList) {
        System.out.println(people.getId() + ":" + people.getName());
    }

    return SUCCESS;
}

}

JSP页面

<s:form action="doUpdate">
    <s:iterator value="peopleList" status="stat" var="people">
        <s:textfield value="%{#people.name}"
            name="peopleList[%{#stat.index}].name" />
        <s:iterator value="states" status="stateStatus" var="personState">
            <s:textfield value="%{#personState.stateAbbr}"
                name="peopleList[%{#stat.index}].states[%{#stateStatus.index}].stateAbbr" label="Abbr State" />
            <br />
        </s:iterator>
    </s:iterator>
    <s:submit value="Submit" />
</s:form>

当我提交此页面时,我的状态是[null],为什么?

2 个答案:

答案 0 :(得分:1)

回答新问题:

如果您的State类没有默认构造函数,则S2 / OGNL将无法实例化该类的空版本。

提供默认(无参数)构造函数,并填充人员状态列表。

(太糟糕了,两个答案都不能被接受;)

答案 1 :(得分:0)

state属性是特定人员的财产。在这种情况下,您需要将状态“连接”到persons[%{#stat.index}],所以:

<s:textfield ... 
    name="persons[%{#stat.index}].states[%{#stateStatus.index}]" .../>

迭代器状态变量具有index属性,可以避免您在IteratorStatus (docs)实例上进行的数学运算:

<s:textfield ... name="persons[%{#stat.index}].name" />

此外,根据您使用的S2版本,您可能不需要#字符。