zoukankan      html  css  js  c++  java
  • springMVC接受对象集合,name数组

    这两天开发遇到一个很常见的问题,即使自己一直没遇见过,不过之前看过是实现接受对象集合的代码,只不过没注意罢了

    推荐一篇文章

    直接贴代码吧

    public class Person {
        private String name;
        private Integer age;
        
        public Person() {
            super();
        }
        public Person(String name, Integer age) {
            super();
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
    }

    之后创建对应的集合model对象,一个bean的list属性

    public class PersonModel {
        private List<Person> persons;
    
        public List<Person> getPersons() {
            return persons;
        }
    
        public void setPersons(List<Person> persons) {
            this.persons = persons;
        }
    
        public PersonModel() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        public PersonModel(List<Person> persons) {
            super();
            this.persons = persons;
        }
    }

    之后对于controller类直接使用personModel对象

    @RequestMapping("test2")
        @ResponseBody
        public void test2(PersonModel persons){
            List<Person> persons2 = persons.getPersons();
            System.out.println(persons2);
        }

    这个时候前端html就有讲究了

    <form action="test2">
        <input type="text" name="persons[0].name" value="a"/>
        <input type="text" name="persons[0].age" value="1"/>
        <input type="text" name="persons[1].name" value="b"/>
        <input type="text" name="persons[1].age" value="2"/>
        <input type="submit" value="提交"/>
    </form>

    []里面的数据保持一致就好,注意需要加.点号

    直接在url中请求

    这种是行不通的

    http://localhost:7080/user/testList?persons[0].name=a&persons[0].age=1&persons[1].name=b&persons[1].age=2

    需要这么请求

    http://localhost:7080/user/testList?persons%5B0%5D.name=a&persons%5B0%5D.age=1&persons%5B1%5D.name=b&persons%5B1%5D.age=2

    ok。

    当然你也可以通过ajax传入json

    后台使用@RequestBody来接受

    对应的xml类型也是可以的。

    倘若接受name数组很简单,直接用数组接受即可

    @RequestMapping("test1")
        @ResponseBody
        public void test1(String[] name,Integer [] age){
            
        }
  • 相关阅读:
    高斯消去法
    【转】sscanf和sprintf是scanf和printf家族的一对成员
    ps电信
    XNA准备篇(一)
    超级BT的SQL2008 在WIN7下附加 SQL2005的数据库
    绘制半口角
    动态的在输入框边上显示可输入的剩余字符数
    CallContext vs. ThreadStatic vs. HttpContext[待翻译]
    Vista 系统下安装 GhostDoc for Visual Studio 2008
    非常优秀的开源框架地址
  • 原文地址:https://www.cnblogs.com/chywx/p/9291477.html
Copyright © 2011-2022 走看看