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){ }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM