1. 在struts框架中常常会遇到多行表单的情况, 如何有效的利用struts框架提供的自动收集机制来处理呢?
2. java
bean代码
public class UserBean implements Serializable {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
自动填充arraylist
import java.util.ArrayList;
public class AutoArrayList<T> extends ArrayList<T>{
private static final long serialVersionUID = -8315597336838709825L;
private Class<T> t =null;
public AutoArrayList(Class t)
{
this.t = t;
}
public AutoArrayList() {
}
public T get(int index)
{
while (index >= size()) {
try {
add(t.newInstance());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return super.get(index);
}
}
form代码
public class TestForm extends ActionForm{
private List<UserBean > userList= new AutoArrayList<UserBean >();
public List getUserList() {
return userList;
}
public void setUserList(List userList) {
this.userList=userList;
}
}
2. JSP页面
方法1: <logic:iterate id="bean" name="testForm" property="beanList" indexId="index">
<TR>
<TD><input name='beanList[<bean:write name="index"/>].id' value='<bean:write name="bean" property="id"/>'></TD>
<TD><input name='beanList[<bean:write name="index"/>].name' value='<bean:write name="bean" property="name"/>'></TD>
<TD><input name='beanList[<bean:write name="index"/>].age' value='<bean:write name="bean" property="age"/>'></TD>
</TR>
</logic:iterate>
方法2:
方法1: <logic:iterate id="bean" name="testForm" property="beanList" indexId="index">
<TR>
<TD ><html:text name="beanList" property="id" indexed="true" /></TD>
<TD ><html:text name="beanList" property="name" indexed="true" /></TD>
<TD ><html:text name="beanList" property="age" indexed="true" /></TD>
</TR>
</logic:iterate>
3.几点说明:
A.strut填充ActionForm的方法:
如果key是简单的'name',直接form.setName(map.get('name'));
如果key是'person.name', 执行的操作是 form.getPerson().setName(map.get('person.name');
如果key是'userList[0].name', 它可以对应到数据或集合中,如对于数组 form.userList[0].name=map.get('userList[0].name'); 对于集合(List) form.getuserList().get(0).setName(map.get('userList[0].name'))