*Edit: I may have to use a list but the same principle applies.

I'm attempting to bind an array to a form using the @ModelAttribute annotation. A table is populated with the contents of the array (each element in the array corresponds to a row in the table). The array may be populated with data or may be empty when it's bound. The user can add rows to the table (which should add elements to the array).

My question is how can elements be added to the array if it's already defined before I pass it in? Will this automagically happen when the form is submitted?

<body>
    <h1>Members</h1>
        <form:form action="configure" modelAttribute="members" method="post" id="member-form">
            <table id="member-table" class="table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="member-table-body">
                    <c:forEach items="${members}" var="member" varStatus="i" begin="0" >
                        <tr class="member">    
                            <td><form:input path="members[${i.index}].name" id="name${i.index}" /></td>
                            <td><a href="#" class="remove">Remove</a></td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
            <input type="submit" value="Save" id="submit" />
            <a href="#" id="add">Add Member</a>
            <a href="?f=">Reset List</a>
        </form:form>   
</body>

__

$(document).ready(function(){
$('#add').click(function(e) {
    e.preventDefault();
    //Add a member

    //Get the number of rows that are in the table
    var memberTable = $('#member-table-body');
    var numRows = memberTable.children('tr').length

    //Add row to the table.
    // memberTable.innerHTML(

    return false;
});
$('.remove').on('click', function(e) {
                e.preventDefault();
                $(this).parent().parent().remove();
                return false;
});

});​

share|improve this question

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

share|improve this answer
Viral..i saw the sample in your website...that seems to be dynamic editing and saving the existing records..but the user question is can we add new rows to the table that increase your list dynamically and when you submit the controller gets the newly added ones in your "contacts" list. – raddykrish Dec 14 '12 at 20:12



출처 - http://stackoverflow.com/questions/13869769/array-modelattribute-expansion-in-spring-mvc








Spring MVC: Multiple Row Form Submit Using List Of Beans

Recently I had a requirement where using Spring MVC we had to take inputs multiple rows of data from user. The form had many rows which user can edit and submit. Spring MVC provides very simple yet elegant way of collecting data from multiple rows from HTML form and store them in List of Beans in Java.

Lets look at the requirement first. We have a screen where data for multiple Contacts is displayed. The Contact data is displayed in an HTML table. Each row in the table represents a single contact. Contact details consist of attributes such as Firstname, Lastname, Email and Phone number.

Related: Spring 3 MVC Tutorial Series (Must Read)

The Add Contact form would look like following:
spring-mvc-multi-row-form

Lets see the code behind this example.

Tools and Technologies used:

  1. Java 5 or above
  2. Eclipse 3.3 or above
  3. Spring MVC 3.0

Step 1: Create Project Structure

Open Eclipse and create a Dynamic Web Project.
eclipse-dynamic-web-project

Enter project name as SpringMVC_Multi_Row and press Finish.

Step 2: Copy Required JAR files

Once the Dynamic Web Project is created in Eclipse, copy the required JAR files under WEB-INF/libfolder. Following are the list of JAR files:
spring-mvc-multi-row-jar-files


Step 3: Adding Spring MVC support

Once the basic project setup is done, we will add Spring 3 MVC support. For that first modify default web.xml and add springs DispatcherServlet.

File: /WebContent/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Spring3MVC-Multi-Row</display-name>
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

Related: Tutorial: Learn Spring MVC Lifecycle

Now add spring-servlet.xml file under WEB-INF folder.

File: /WebContent/WEB-INF/spring-servlet.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
         
    <context:annotation-config />
    <context:component-scan base-package="net.viralpatel.spring3.controller" />  
 
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Note that in above spring-servlet file, line 10, 11 defines context:annotation-config and component-scan tags. These tags let Spring MVC knows that the spring mvc annotations are used to map controllers and also the path from where the controller files needs to be loaded. All the files below packagenet.viralpatel.spring3.controller will be picked up and loaded by spring mvc.

Step 4: Add Spring Controller and Form classes

File: /src/net/viralpatel/spring3/form/Contact.java

package net.viralpatel.spring3.form;
 
public class Contact {
    private String firstname;
    private String lastname;
    private String email;
    private String phone;
 
    public Contact() {
    }
 
    public Contact(String firstname, String lastname, String email, String phone) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.email = email;
        this.phone = phone;
    }
     
    // Getter and Setter methods
}

File: /src/net/viralpatel/spring3/form/ContactForm.java

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

Note line 7 in above code how we have defined a List of bean Contact which will hold the multi-row data for each Contact.

File: /src/net/viralpatel/spring3/controller/ContactController.java

package net.viralpatel.spring3.controller;
 
import java.util.ArrayList;
import java.util.List;
 
import net.viralpatel.spring3.form.Contact;
import net.viralpatel.spring3.form.ContactForm;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class ContactController {
 
     
    private static List<Contact> contacts = new ArrayList<Contact>();
 
    static {
        contacts.add(new Contact("Barack", "Obama", "barack.o@whitehouse.com", "147-852-965"));
        contacts.add(new Contact("George", "Bush", "george.b@whitehouse.com", "785-985-652"));
        contacts.add(new Contact("Bill", "Clinton", "bill.c@whitehouse.com", "236-587-412"));
        contacts.add(new Contact("Ronald", "Reagan", "ronald.r@whitehouse.com", "369-852-452"));
    }
     
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public ModelAndView get() {
         
        ContactForm contactForm = new ContactForm();
        contactForm.setContacts(contacts);
         
        return new ModelAndView("add_contact" , "contactForm", contactForm);
    }
     
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView save(@ModelAttribute("contactForm") ContactForm contactForm) {
        System.out.println(contactForm);
        System.out.println(contactForm.getContacts());
        List<Contact> contacts = contactForm.getContacts();
         
        if(null != contacts && contacts.size() > 0) {
            ContactController.contacts = contacts;
            for (Contact contact : contacts) {
                System.out.printf("%s \t %s \n", contact.getFirstname(), contact.getLastname());
            }
        }
         
        return new ModelAndView("show_contact", "contactForm", contactForm);
    }
}

In above ContactController class, we have defile two methods: get() and save().

get() method: This method is used to display Contact form with pre-populated values. Note we added a list of contacts (Contacts are initialize in static block) in ContactForm bean object and set this inside aModelAndView object. The add_contact.jsp is displayed which in turns display all contacts in tabular form to edit.

save() method: This method is used to fetch contact data from the form submitted and save it in the static array. Also it renders show_contact.jsp file to display contacts in tabular form.

Step 5: Add JSP View files

Add following files under WebContent/WEB-INF/jsp/ directory.

File: /WebContent/WEB-INF/jsp/add_contact.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Spring 3 MVC Multipe Row Submit - viralpatel.net</title>
</head>
<body>
 
<h2>Spring MVC Multiple Row Form Submit example</h2>
<form:form method="post" action="save.html" modelAttribute="contactForm">
    <table>
    <tr>
        <th>No.</th>
        <th>Name</th>
        <th>Lastname</th>
        <th>Email</th>
        <th>Phone</th>
    </tr>
    <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>
</table
<br/>
<input type="submit" value="Save" />
     
</form:form>
</body>
</html>

In above JSP file, we display contact details in a table. Also each attribute is displayed in a textbox. Note that modelAttribute=”contactForm” is defined in <form:form /> tag. This tag defines the modelAttribute name for Spring mapping. On form submission, Spring will parse the values from request and fill the ContactForm bean and pass it to the controller.

Also note how we defined textboxes name. It is in form contacts[i].a. Thus Spring knows that we want to display the List item with index i and its attribute a.

contacts[${status.index}].firstname will generate each rows as follows:

contacts[0].firstname // mapped to first item in contacts list
contacts[1].firstname // mapped to second item in contacts list
contacts[2].firstname // mapped to third item in contacts list

Spring 3 MVC and path attribute and square bracket

One thing here is worth noting that we haven’t used Spring’s 
tag to render textboxes. This is because Spring MVC 3 has a unique way of handling path attribute for 
tag. If we define the textbox as follows:

<form:input path="contacts[${status.index}].firstname" />

Then instead of converting it to following HTML code:

<input name="contacts[0].firstname" />
<input name="contacts[1].firstname" />
<input name="contacts[2].firstname" />

It converts it into following:

<input name="contacts0.firstname" />
<input name="contacts1.firstname" />
<input name="contacts2.firstname" />

Note how it removed square brackets [ ] from name attribute. In previous versions of Spring (before 2.5) the square bracket were allowed in name attribute.

It seems w3c has later changed the HTML specification and removed [ ] from html input name.
Read the specification http://www.w3.org/TR/html4/types.html#type-name. It clearly says that:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (“-”), underscores (“_”), colons (“:”), and periods (“.”).

Thus, square brackets aren’t allowed in name attribute! And thus Spring 3 onwards this was implemented.

So far I haven’t got any workaround to use springs <form:input /> tag instead of plain html <input /> to render and fetch data from multiple rows.

File: /WebContent/WEB-INF/jsp/show_contact.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Spring 3 MVC Multipe Row Submit - viralpatel.net</title>
</head>
<body>
<h2>Show Contacts</h2>
<table width="50%">
    <tr>
        <th>Name</th>
        <th>Lastname</th>
        <th>Email</th>
        <th>Phone</th>
    </tr>
    <c:forEach items="${contactForm.contacts}" var="contact" varStatus="status">
        <tr>
            <td>${contact.firstname}</td>
            <td>${contact.lastname}</td>
            <td>${contact.email}</td>
            <td>${contact.phone}</td>
        </tr>
    </c:forEach>
</table
<br/>
<input type="button" value="Back" onclick="javascript:history.back()"/>
</body>
</html>

File: /WebContent/index.jsp

<jsp:forward page="get.html"></jsp:forward>


Final Project Structure

Once we have added all relevant source files and jar files, the project structure should look like following:
spring-multi-row-project-structure


Step 6: Execute it

Execute the web application Right click on project > Run As > Run on Server.

Add Contact page

Show Contact page
spring-multiple-row-list-show-page

Download Source Code

Spring-MVC-Multiple-Row-List-example.zip (2.9 MB)



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







Posted by linuxism
,