`

spring mvc 封装list到后台 SpringMVC_Multi_Row

阅读更多
spring mvc 封装list到后台
参考:http://viralpatel.net/blogs/spring-mvc-multi-row-submit-java-list/

Spring MVC: Multiple Row Form Submit Using List Of Beans
By Viral Patel on December 1, 2011
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:

Lets see the code behind this example.
Tools and Technologies used:
Java 5 or above
Eclipse 3.3 or above
Spring MVC 3.0
Step 1: Create Project Structure
Open Eclipse and create a 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/lib folder. Following are the list of 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 package net.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 a ModelAndView 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:


Step 6: Execute it
Execute the web application Right click on project > Run As > Run on Server.
Add Contact page

Show Contact page

Download Source Code
Spring-MVC-Multiple-Row-List-example.zip (2.9 MB)
Related Posts
Spring MVC HashMap Form Integration example
Spring 3 MVC: Handling Forms in Spring 3.0 MVC
Spring 3 MVC: Internationalization & Localization Tutorial with Example
Spring MVC Multiple File Upload example
Change spring-servlet.xml Filename (Spring Web Contenxt Configuration Filename)
Tutorial:Create Spring 3 MVC Hibernate 3 Example using Maven in Eclipse
Spring MVC Flash Attribute tutorial with example
分享到:
评论

相关推荐

    spring_mvc.zip_Spring学生_spring mvc_springmvc 学生_springmvc 系统

    【Spring MVC 学生管理系统详解】 Spring MVC 是一个基于 Spring 框架的模型-视图-控制器(MVC)架构,它简化了在 Java Web 应用中的开发工作。在"spring_mvc.zip"中,我们可以看到一个针对学生管理系统的实例代码...

    spring_mvc.zip_spring_spring mvc_springmvc_springmvc架构

    Spring MVC 是一个基于Java的轻量级Web应用框架,它是Spring框架的重要组成部分,主要用于构建控制器层,实现模型-视图-控制器(MVC)的设计模式。这个“spring_mvc.zip”压缩包很可能是为了帮助初学者快速入门...

    Spring MVC 教程_springmvc_spring_

    深入 分析V1.1.rar

    基于Java语言的Spring MVC框架开发之springmvc_demo设计源码

    该项目为基于Java语言的Spring MVC框架开发的springmvc_demo项目,包含65个文件,涵盖19个Java源文件、10个XML配置文件、7个HTML文件、6个Shell脚本、5个JSP文件、3个CSS文件、3个JPG图片文件、1个Git忽略文件、1个...

    MVC.rar_SpringMVC Struts_java MVC_mvc_spring-aspects-3.2.2_spri

    标题"MVC.rar_SpringMVC_Struts_java_MVC_mvc_spring-aspects-3.2.2_sprin"指的是一个包含多个MVC框架相关的示例项目,主要涉及SpringMVC、Struts以及Java MVC模式。这个压缩包可能是用于教学或演示如何在实际开发中...

    springmvc_spring_mybatis框架整合文档

    整合springmvc_spring_mybatis框架后整理的学习笔记以及整合方法。

    demo_SpringMVC.rar_+SpringMVC demo_DEMO_spring mvc_spring mvc de

    本示例项目 "demo_SpringMVC" 提供了一个基础的 Spring MVC 示例,旨在帮助开发者了解和学习如何使用该框架进行开发。 在 Spring MVC 中,`Model` 负责存储数据,`View` 负责渲染数据,而 `Controller` 则是处理...

    springmvc_mybatis1208

    本教程“springmvc_mybatis1208”应该包含了从基础概念到实战案例的详细讲解,是学习和掌握这两者整合的宝贵资源。 为了更好地学习和实践,你可以通过提供的视频地址(http://dvd.boxuegu.com/course/8.html)观看...

    springmvc_jpbm5_document.zip_spring mvc

    标题 "springmvc_jpbm5_document.zip_spring mvc" 提供的信息暗示了这是一个关于Spring MVC框架的学习资源压缩包,包含文档和代码示例。描述中提到“spring学习,java spring mvc 学习代码,文档”,这表明内容涵盖...

    SSM.zip_mybatis_spring_springMVC mybatis_springmvc_ssm

    标题 "SSM.zip_mybatis_spring_springMVC mybatis_springmvc_ssm" 提供了一个关于集成框架的线索,即Spring、SpringMVC和MyBatis的整合应用,通常称为SSM框架。这个框架是Java开发Web应用程序的常用组合,特别是对于...

    spring_mvc_ajax.zip_SpringMVC ajax_SpringMVC+ajax_spring ajax_sp

    本压缩包“spring_mvc_ajax.zip”包含了关于如何结合SpringMVC框架与Ajax技术来实现异步请求的示例和资源。下面将详细介绍这两个技术及其相互配合的应用。 SpringMVC是Spring框架的一部分,它是一个轻量级的模型-...

    Springmvc_Demo

    总结起来,`Springmvc_Demo` 项目通过 `springmvc_demo_03` 和 `springmvc_demo_04` 两个实例,展示了 Spring MVC 的手动配置与注解驱动的使用,涵盖了 MVC 架构的基本概念、核心组件、注解应用以及其在实际开发中的...

    SpringMvc_Maven.zip_java项目_maven_maven springmvc_springmvc maven

    在本项目 "SpringMvc_Maven.zip" 中,我们将看到如何在一个 Maven 项目中配置并使用 Spring MVC。 首先,我们来详细讨论 Maven。Maven 是一个项目管理和综合工具,它通过提供一个标准化的项目对象模型(Project ...

    SpringMVC_Upload.rar_shipvu7_springmvc_springmvc upload

    总的来说,"SpringMVC_Upload.rar_shipvu7_springmvc_springmvc upload"示例涉及了Spring MVC框架下的多文件上传、返回值处理以及与数据库交互的关键知识点。通过学习和实践这些内容,你可以构建出健壮的Web应用程序...

    springmvc_day01

    "springmvc_day01" 可能是某个课程或学习资源的第一天内容,主要关注于注解驱动的开发方式,即如何使用注解来简化配置,使得在最新的 Spring MVC 版本中处理器映射器和处理器适配器的配置更加直观和简洁。...

    SpringIOC_SpringMVC_SpringAnnotation_JPA

    标题 "SpringIOC_SpringMVC_SpringAnnotation_JPA" 涵盖了四个核心的Java开发框架技术,它们是Spring框架的重要组成部分。Spring框架是一个全面的企业级应用开发框架,提供了许多功能,包括依赖注入(Dependency ...

    springmvc_day02

    在“springmvc_day02”的主题下,我们将深入探讨视图解析器(View Resolver)这一核心组件,它在Spring MVC中扮演着至关重要的角色,简化了控制器(Controller)中的视图逻辑。 视图解析器的主要任务是将逻辑视图名...

    ssmbuild_springmvc_spring_bootstrap_mybatis_

    这个项目名为"ssmbuild_springmvc_spring_bootstrap_mybatis_",它是一个整合了Spring MVC、Spring和MyBatis的小型示例,旨在展示如何将这些框架集成到一个应用中。前端界面采用了Bootstrap,提供了美观且响应式的...

Global site tag (gtag.js) - Google Analytics