如何在spring< form:form>中保存许多对象 [英] How to save many objects in a spring <form:form>
本文介绍了如何在spring< form:form>中保存许多对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@Component
@Entity
@Table(name="menu")
@Configurable
public class Menu implements Serializable{
....
@OneToMany(mappedBy="menu", fetch=FetchType.EAGER)
private Set<VoceMenu> voceMenuList;
public Set<VoceMenu> getVoceMenuList() {
return voceMenuList;
}
public void setVoceMenuList(Set<VoceMenu> voceMenuList) {
this.voceMenuList = voceMenuList;
}
.....
}
我以这种方式打印表单来编辑菜单及其相对的VoceMenu对象:
I print a form to edit the menu, and its relative VoceMenu objects, this way:
<form:form action="editMenu" method="post" commandName="menu">
Menu id<form:input path="id" maxlength="11"/><br/>
......
<c:forEach items="${menu.voceMenuList}" varStatus="counter">
<form:input path="voceMenuList[${counter.index}].id" maxlength="11"/>
.....
</c:forEach>
<input type="submit">
</form:form>
但是,当我尝试保存对象菜单时,出现此错误:
But, when I try to save the object Menu, I get this error:
Bean类[com.springgestioneerrori.model.Menu]的无效属性'voceMenuList [0]':无法 从大小为0的集合中获取索引为0的元素, 使用属性路径"voceMenuList [0]"访问
Invalid property 'voceMenuList[0]' of bean class [com.springgestioneerrori.model.Menu]: Cannot get element with index 0 from Set of size 0, accessed using property path 'voceMenuList[0]'
推荐答案
不能通过索引访问Set的元素.您将需要添加一些方法,这些方法将返回一个包含您的集合的列表.
The elements of a Set cannot be accessed by index. You will need to add methods which return a List wrapping your set.
@Component
@Entity
@Table(name="menu")
@Configurable
public class Menu implements Serializable{
....
@OneToMany(mappedBy="menu", fetch=FetchType.EAGER)
private Set<VoceMenu> voceMenus;
public Set<VoceMenu> getVoceMenus() {
return voceMenus;
}
public void setVoceMenus(Set<VoceMenu> voceMenus) {
this.voceMenus = voceMenus;
}
//bind to this
public List<VoceMenu> getVoceMenusAsList(){
return new ArrayList<VoceMenu>(voceMenus);
}
.....
}
JSP:
<form:form action="editMenu" method="post" commandName="menu">
Menu id<form:input path="id" maxlength="11"/><br/>
......
<c:forEach items="${menu.voceMenusAsList}" varStatus="counter">
<form:input path="voceMenusAsList[${counter.index}].id" maxlength="11"/>
.....
</c:forEach>
<input type="submit">
</form:form>
这篇关于如何在spring< form:form>中保存许多对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文