How to send list of Objects to View and back to Po

2020-01-24 07:11发布

问题:

Suppose I have class Person, I made a list of Person instances and add this list to a Model.

List<Person> persons = new ArrayList<Person>();
model.addAttribute("persons",persons);
return "savePersons";

In the View page I have a form:

<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>

When I click on the submit button I want to bind the Person List to the POST method on the controller..

@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";
}

but the persons list is not binding/fetching at the POST method.

Is it possible to bind a list objects in this way or is there an alternative for this?

回答1:

I think this link will help you set up what you are trying to do:

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

It looks like in your form you need to modify it to something like:

<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>

This SO question has a pretty good example that might help you out too: List<Foo> as form backing object using spring 3 mvc, correct syntax?



回答2:

As Shri mentioned in his comment on ssn771 answer that if your binding list is more then 256 then it gives error like

org.springframework.beans.InvalidPropertyException : Invalid property 'mylist[256]' of bean class [com.app.MyPageListVO]: Index of out of bounds in property path 'mylist[256]'; nested exception is java.lang.IndexOutOfBoundsException: Index: 256, Size: 256 at org.springframework.beans.BeanWrapperImpl.getPrope rtyValue(BeanWrapperImpl.java:830) at...

This error occurs because by default 256 is limit for array and collection auto-growing to avoid OutOfMemoryErrors, But you can increase this limit by setting WebDataBinder's AutoGrowCollectionLimit property in @InitBinder in that controller.

Code:

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