如何在 <form:input> 中打印作为表单主要对象字段的 Set 的值

How to print in a <form:input> the value of Set that is a field of the main object of the form

我有一个名为菜单的对象。它有一个名为 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;
    }
    .....   
}

我正在尝试构建一个表单来保存或更新菜单。我做了一些 link 这个:

<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[=27 中找到 属性 voceMenu =] bean,你应该使用 JSTL 的状态对象,比如

<c:forEach items="${menu.voceMenuList}" var="voceMenu" varStatus="count">

<form:input path="voceMenuList[${count.index}].id" maxlength="11"/>

为了正确绑定值

更新您的评论

您面临的进一步问题与动态添加到集合有关,这个 post 解释得很好,并列出了可能的解决方案 Spring 3 MVC: one-to-many within a dynamic form (add/remove on create/update)

您始终可以选择使用表单支持 bean,然后填充您的实体。它将帮助您缓解这个问题,并将您的视图与实体分离,例如使其更稳健地应对 属性 名称更改