在struts框架中常常会遇到多行表单的情况, 如何有效的利用struts框架提供的自动收集机制来处理呢? 这里提供一个示例.
1.示例功能:通过一个【提交】按钮保存多行人员信息,如附件中的图片所示。
2.核心类代码:
TestForm.java
Java代码
public class TestForm extends ActionForm{
private List voList = null;
public List getVoList() {
return voList;
}
public void setVoList(List voList) {
this.voList=voList;
}
}
public class TestForm extends ActionForm{
private List voList = null;
public List getVoList() {
return voList;
}
public void setVoList(List voList) {
this.voList=voList;
}
}
PreAction.java:准备初始数据
Java代码
public class PreAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
TestForm aform = (TestForm)form;
TestVo vo1=new TestVo("1","vo1","11");
TestVo vo2=new TestVo("2","vo2","22");
TestVo vo3=new TestVo("3","vo3","33");
List voList = new ArrayList();
voList.add(vo1);
voList.add(vo2);
voList.add(vo3);
aform.setVoList(voList);
return mapping.findForward("jsp1");
}
}
public class PreAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
TestForm aform = (TestForm)form;
TestVo vo1=new TestVo("1","vo1","11");
TestVo vo2=new TestVo("2","vo2","22");
TestVo vo3=new TestVo("3","vo3","33");
List voList = new ArrayList();
voList.add(vo1);
voList.add(vo2);
voList.add(vo3);
aform.setVoList(voList);
return mapping.findForward("jsp1");
}
}
jsp1.jsp:编辑保存的页面
Java代码
This is jsp1.Edit
id
name
age
This is jsp1.Edit
id
name
age
SaveAction.java:保存多行数据
Java代码
public class SaveAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
TestForm aform = (TestForm)form;
List voList=aform.getVoList();
//TODO:you can save data to database here.
request.setAttribute("voList", voList);
return mapping.findForward("jsp2");
}
}
public class SaveAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
TestForm aform = (TestForm)form;
List voList=aform.getVoList();
//TODO:you can save data to database here.
request.setAttribute("voList", voList);
return mapping.findForward("jsp2");
}
}
jsp2.jsp:展示保存结果
Java代码
This is jsp2.View