Array @ModelAttribute expansion in Spring MVC

一个人想着一个人 提交于 2019-12-06 13:29:23

You need to create a Model class wrapping the List and use this Model in your controller.

Something like:

package net.viralpatel.spring3.form;

import java.util.List;

public class ContactForm {

    private List<Contact> contacts;

    public List<Contact> getContacts() {
        return contacts;
    }

    public void setContacts(List<Contact> contacts) {
        this.contacts = contacts;
    }
}

And then use this in JSP as:

<c:forEach items="${contactForm.contacts}" var="contact" varStatus="status">
    <tr>
        <td align="center">${status.count}</td>
        <td><input name="contacts[${status.index}].firstname" value="${contact.firstname}"/></td>
        <td><input name="contacts[${status.index}].lastname" value="${contact.lastname}"/></td>
        <td><input name="contacts[${status.index}].email" value="${contact.email}"/></td>
        <td><input name="contacts[${status.index}].phone" value="${contact.phone}"/></td>
    </tr>
</c:forEach>

See this tutorial: Spring MVC: Multiple Row Form Submit using List of Beans

This cannot be done automagically by Spring for you. Actually you are not binding any thing here. You are iterating the array using the JSTL EL and setting it to the text field. Ideally how this can be handled is you need to prepare the whole table as a json string and submit to the backend, parse over there and get to know how many have been added/deleted/updated. You can have a hidden column to maintain this state and identify in the backend. I dont think the array gets expanded automatically in the front end. This is my 2 cents.

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