3

我需要在表单中放入可变数量的相同类型的字段。假设我有一个命令对象

public class Person
  String name;
  String surname;

// getters and setters

和一个jsp

<form:form command="personCommand">
  <form:input path="name"/>
  <form:input path="surname"/>
</form:form>

当我有静态数量的字段时,这是标准方式。但是如果我有类似的东西怎么办

<form:form command="personCommand">
  <c:forEach items="${persons}">
    <form:input path="name"/>
    <form:input path="surname"/>
  </c:forEach>
</form:form>

(这当然是不正确的)其中人数事先不知道?Spring中是否有某种方法可以绑定数组或列表中的字段?或者某种解决方法(目前我正在使用 javascript 连接字段并以编程方式将它们分开,这是丑陋的)。

4

1 回答 1

1

You can create a class(PersonWrapper) and include the List of persons as a variable in that class. Then in JSP, you can use the following syntax

<c:forEach items="${personWrapper.persons}" varStatus="i">
  <form:input path="persons[${i.index}].name"/>
  <form:input path="persons[${i.index}].surname"/>
</c:forEach>

Then in the controller, you can get the values in List of persons

于 2012-12-06T08:54:38.637 回答