Dynamically binding lists with Spring's form tag

喜欢而已 提交于 2019-12-03 08:26:44

问题


I have a command object FaxForm and it holds a list of FaxStatus objects inside a faxStatusList property.

public class FaxForm {
  private List<FaxStatus> faxStatusList;
  public void setFaxStatusList(List<FaxStatus> faxStatusList) {
    this.faxStatusList = faxStatusList;
  }
  public List<FaxStatus> getFaxStatusList() {
    return faxStatusList;
  }
}

I initially had a JSP page that would bind the objects by performing the following:

<c:forEach items="${esaFaxForm.faxStatusList}" var="item" varStatus="loop">
  <tr class="tableAltBackground">
    <td>
      <form:checkbox path="faxStatusList[${loop.index}].selected"/>
    </td>
    <td>
      <form:select path="faxStatusList[${loop.index}].status" items="${esaFaxForm.statusOptions}" onchange="checkThisBox(this);"/>
    </td>
    <td>
      <a href="${statusContUrl}?id=${item.id}&status=${item.status}" onclick="openFaxWindow('${viewFaxUrl}?id=${item.id}', ${loop.index});">${item.name}</a>
      <form:hidden path="faxStatusList[${loop.index}].name"/>
    </td>
    <td>
      <a href="${statusContUrl}?id=${item.id}&status=${item.status}" onclick="openFaxWindow('${viewFaxUrl}?id=${item.id}', ${loop.index});">${item.id}</a>
      <form:hidden path="faxStatusList[${loop.index}].id"/>
    </td>
  </tr>
</c:forEach>

However, I am trying to figure out how I could do the binding without the forEach loop and index. The examples on the Spring website show the binding by setting the path to the list name. Is there a way to bind the properties? I've tried this but it fails:

<form:checkbox path="faxStatusList.faxStatus.selected"/>
<form:select path="faxStatusList.faxStatus.status" items="${esaFaxForm.statusOptions}"/>

The faxStatusList has a getter and setter method and the FaxStatus variables each have getter/setter properties. I get the error "Invalid property 'faxStatusList.faxStatus' of bean class..."


回答1:


Spring form tags has a checkboxes tag. You can use it as follows to do the binding automatically:

<form:checkboxes items="${faxStatusList}" path="faxStatusList" itemLabel="name" itemValue="id" delimiter="<br/>" onclick="yourOnClickMethodIfYouNeed(this);"/>

The above snippet will display a list of checkbox items delimited with the br tag. Any changes made to the state of the checkboxes will be reflected appropriately in your FaxForm. faxStatusList object.



来源:https://stackoverflow.com/questions/1934129/dynamically-binding-lists-with-springs-form-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!