我可以通過讓另一個POJO作爲一個容器與您的POJO列表一起實現。
這應該是這樣的:
public class PojoForm {
private List<Pojo> pojos;
public List<Pojo> getPojos() {
return pojos;
}
public void setPojos(List<Pojo> pojos) {
this.pojos = pojos;
}
}
然後在控制器上,使用此容器而不是實際的POJO作爲一個模型屬性。
@ModelAttribute("pojoForm")
public PojoForm populatePojos() {
// Don't forget to initialize the pojos list or else it won't work
PojoForm pojoForm = new PojoForm();
List<Pojo> pojos = new ArrayList<Pojo>();
for(int i=0; i<2; i++) {
pojos.add(new Pojo());
}
pojoForm.setPojos(pojos);
return pojoForm;
}
@RequestMapping(method=RequestMethod.POST)
public String saveForm(@ModelAttribute("pojoForm") PojoForm pojoForm) {
for(Pojo pojo : pojoForm.getPojos()) {
service.save(pojo);
}
return "theview.jsp";
}
然後在視圖應該是這個樣子:
<form:form commandName="pojoForm" method="POST">
<!-- Pojo 1 -->
<form:input path="pojos[0].a" />
<form:input path="pojos[0].b" />
<form:input path="pojos[0].c" />
<!-- Pojo 2 -->
<form:input path="pojos[1].a" />
<form:input path="pojos[1].b" />
<form:input path="pojos[1].c" />
</form:form>
a,b和c是POJO類的屬性。
您也可以在列表中這樣直接循環:
<form:form commandName="pojoForm" method="POST">
<c:forEach items="${pojoForm.pojos}" varStatus="i">
<form:input path="pojos[${i.index}].a" />
<form:input path="pojos[${i.index}].b" />
<form:input path="pojos[${i.index}].c" />
</c:forEach>
</form:form>
使用索引的屬性:數據[0] .name和例如。請參閱http://stackoverflow.com/questions/1429760/command-objects-in-spring –