且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring 3 MVC-高级数据绑定-带有简单对象列表的表单请求

更新时间:2023-10-05 17:56:46

您的jQuery ajax调用会产生以下application/x-www-form-urlencoded请求正文(采用%解码形式):

Your jQuery ajax call produces the following application/x-www-form-urlencoded request body (in %-decoded form):

people[0][name]=dave&people[0][age]=15&people[1][name]=pete&people[1][age]=12&people[2][name]=steve&people[2][age]=24

Spring MVC可以将以数字索引的属性绑定到List,将以字符串索引的属性绑定到Map.您在这里需要自定义对象,因为@RequestParam不支持复杂类型.因此,您有:

Spring MVC can bind properties indexed with numbers to Lists and properties indexed with strings to Maps. You need the custom object here because @RequestParam doesn't support complex types. So, you have:

public class People {
    private List<HashMap<String, String>> people;

    ... getters, setters ...
}

@RequestMapping("/controllerMethod", method=RequestMethod.POST)        
public String doSomething(People people) {        
    ...
} 

您还可以在发送数据之前将数据序列化为JSON,然后按照Bozho的建议使用@RequestBody.您可以在 mvc-showcase示例中找到此方法的示例. .

You can also serialize data into JSON before sending them and then use a @RequestBody, as Bozho suggests. You may find an example of this approach in the mvc-showcase sample.