如何在控制器中发送要查看的对象列表并返回到Post方法

Amo*_*ogh 31 java post spring-mvc

假设我有课程Person,我制作了一个Person实例列表并将此列表添加到a Model.

List<Person> persons = new ArrayList<Person>();
model.addAttribute("persons",persons);
return "savePersons";
Run Code Online (Sandbox Code Playgroud)

View页面中我有一个表单:

<form:form method="post" action="savePerson" modelAttribute="persons">
    <c:forEach var="person" items="${persons}">
        <form:input path="person.FName" name="FName" id="FName" value="" />
        <form:input path="person.LName" name="LName" id="LName" value="" />
    </c:forEach>

    <button type="submit"></button>
</form:form>
Run Code Online (Sandbox Code Playgroud)

当我单击提交按钮时,我想绑定Person List到控制器上的POST方法.

@RequestMapping(value = { "savePerson" }, method = RequestMethod.POST)
public String savePerson(Model model, HttpServletRequest request,
        HttpSession session,@ModelAttribute("persons")List<Person> persons) {
    System.out.println(persons.length);
    return "success";
}
Run Code Online (Sandbox Code Playgroud)

但该persons方法没有绑定/获取列表POST.

是否可以以这种方式绑定列表对象,或者有替代方法吗?

ssn*_*771 51

我认为此链接将帮助您设置您要执行的操作:

http://viralpatel.net/blogs/spring-mvc-multi-row-submit-java-list/

在您的表单中,您需要将其修改为:

<form:form method="post" action="savePerson" modelAttribute="persons">
    <c:forEach var="person" items="${persons}" varStatus="status">
        <form:input path="person[${status.index}].FName" name="FName" id="FName" value="" />
        <form:input path="person[${status.index}].LName" name="LName" id="LName" value="" />
    </c:forEach>
Run Code Online (Sandbox Code Playgroud)

这个SO问题有一个非常好的例子可能会帮助你:使用spring 3 mvc列出<Foo>作为表单支持对象,语法是否正确?

  • 只是想知道 form:input path 语句是人(带有 as)吗?人[${status.index}] (2认同)
  • 但如果列表大小超过256,则会失败. (2认同)

Amo*_*ogh 18

正如Shri在他对ssn771的评论中提到的那样,如果你的绑定列表超过256,那么就会给出错误

org.springframework.beans.InvalidPropertyException:bean类[com.app.MyPageListVO]的属性'mylist [256]'无效:属性路径'mylist [256]'中的越界索引; 嵌套异常是java.lang.IndexOutOfBoundsException:索引:256,大小:256 org.springframework.beans.BeanWrapperImpl.getPrope rtyValue(BeanWrapperImpl.java:830)at ...

发生此错误是因为默认情况下256是数组和集合自动增长的限制以避免 OutOfMemoryErrors,但您可以通过@InitBinder在该控制器中设置WebDataBinder的AutoGrowCollectionLimit属性来增加此限制.

码:

@InitBinder
public void initBinder(WebDataBinder dataBinder) {
    // this will allow 500 size of array.
    dataBinder.setAutoGrowCollectionLimit(500);
}
Run Code Online (Sandbox Code Playgroud)