Spring MVC 方法参数是list

来源:互联网 发布:古生物学就业 知乎 编辑:程序博客网 时间:2024/06/10 22:57

今天遇到这样一个需求:html页面有两组在数据库里属性名是相同的数据需要同时传到后台,由于条数较多,考虑采用form表单提交。但是问题来了,form表单提交是根据“name”属性来的,如果在form表单里写两个相同的name的input前面那个必然被后面那个覆盖。如果用不同的name那么后台方法参数定义的javaBean就需要多写一倍的属性,而且插入数据库也不方便。于是在想能否后台参数的javaBean定义成lIst来接受。

查了一下找到方法 先在后台定义一个javaBean(TestDTO)把需要传的值都封装到里面,然后再定义一个javaBean(BigDTO) ,把List<TestDTO> test作为该javaBean 的参数;这样就可以提交表单后台转换为javaBean ,从javaBean 中取出LIST.

     TestDTO:

public class TestDTO {private String test1;private String test2;public String getTest1() {return test1;}public void setTest1(String test1) {this.test1 = test1;}public String getTest2() {return test2;}public void setTest2(String test2) {this.test2 = test2;}}
BigDTO:

import java.util.ArrayList;import java.util.List;public class BigDTO implements java.io.Serializable{/** *  */private static final long serialVersionUID = 1L;List<TestDTO> test = new ArrayList<TestDTO>();public List<TestDTO> getTest() {return test;}public void setTest(List<TestDTO> test) {this.test = test;}    }

controller方法

@RequestMapping(value = "/testform")public @ResponseBody void testform(BigDTO famDTO) throws Exception {System.out.println(famDTO.getTest().get(0).getTest1()+" "+famDTO.getTest().get(1).getTest1());} 


html页面

<form name="testForm" action="http://localhost:8080/project/user/testform" method="post">    <input type="text" value="11" name="testDTO[0].test1">    <input type="text" value="22" name="testDTO[1].test1">    <input type="text" value="33" name="testDTO[0].test2">    <input type="text" value="44" name="testDTO[1].test2">    <input type="submit"></form>




0 0
原创粉丝点击