我有一个名为菜单的对象。它有一个名为 voceMenuList 的字段,它是一个 Set
@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;
}
.....
}
我正在尝试构建一个表单来保存或更新菜单。我做了一些链接:
<form:form action="editMenu" method="post" commandName="menu">
......
<c:forEach items="${menu.voceMenuList}" varStatus="counter">
<form:input path="voceMenuList[${counter.index}].id" maxlength="11"/>
.....
但是,当我尝试保存对象菜单时,出现此错误:
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]'
我处理forEach
的方式不正确
最佳答案
该路径与您的 commandName 相关,并且您遇到了问题,因为框架正在尝试在您的 Menu bean 中查找属性 voceMenu
,您应该使用 JSTL 的状态对象,例如
<c:forEach items="${menu.voceMenuList}" var="voceMenu" varStatus="count">
并且比
<form:input path="voceMenuList[${count.index}].id" maxlength="11"/>
为了正确绑定(bind)值
更新您的评论
您面临的进一步问题与动态添加到集合有关,这篇文章很好地解释了它,并列出了可能的解决方案 Spring 3 MVC: one-to-many within a dynamic form (add/remove on create/update)
您始终可以选择使用表单支持 bean,然后填充您的实体。它将帮助您缓解这个问题,并将您的 View 与实体分离,例如使其对属性名称更改更加稳健
关于java - 如何以 <form :input> the value of Set that is a field of the main object of the form 打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28497072/