springMVC accepts a collection of objects, an array of names

springMVC accepts a collection of objects, an array of names

I have encountered a very common problem in the past two days of development. Even though I have never encountered it, I have seen the code to implement the collection of objects before, but I just didn’t pay attention.

Recommend an article

Just post the code

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

Then create the corresponding collection model object, the list attribute of a bean

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

Then use the personModel object directly for the controller class

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

At this time, the front-end html is exquisite

<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="Submit"/>
</form>

[] It’s good to keep the data in the same way, pay attention to the dot

ok.

Of course you can also pass in json through ajax

Use @RequestBody to accept in the background

The corresponding xml type is also possible.

If it is easy to accept the name array, just use the array to accept it

@RequestMapping("test1")
    @ResponseBody
    public void test1(String[] name,Integer [] age){
        
    }
Reference: https://cloud.tencent.com/developer/article/1335841 springMVC accepts object collection, name array-Cloud + Community-Tencent Cloud