我已经阅读了所有Spring 3 Web文档:http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/spring-web.html但是完全无法找到有关绑定更复杂的请求数据的任何有趣文档,例如,假设我使用jQuery发布到控制器如此:
$.ajax({
url: 'controllerMethod',
type: "POST",
data : {
people : [
{
name:"dave",
age:"15"
} ,
{
name:"pete",
age:"12"
} ,
{
name:"steve",
age:"24"
} ]
},
success: function(data) {
alert('done');
}
});
我如何通过控制器接受?最好不必创建自定义对象,我宁愿只能使用简单的数据类型,但是如果我需要自定义对象来简化操作,那我也很好。
为了帮助您入门:
@RequestMapping("/controllerMethod", method=RequestMethod.POST)
public String doSomething() {
System.out.println( wantToSeeListOfPeople );
}
不要担心这个问题的回复,我关心的只是处理请求,我知道如何处理回复。
编辑:
我有更多示例代码,但我无法让它工作,我在这里缺少什么?
选择javascript:
var person = new Object();
person.name = "john smith";
person.age = 27;
var jsonPerson = JSON.stringify(person);
$.ajax({
url: "test/serialize",
type : "POST",
processData: false,
contentType : 'application/json',
data: jsonPerson,
success: function(data) {
alert('success with data : ' + data);
},
error : function(data) {
alert('an error occurred : ' + data);
}
});
控制器方法:
public static class Person {
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
String name;
Integer age;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@RequestMapping(value = "/serialize")
@ResponseBody
public String doSerialize(@RequestBody Person body) {
System.out.println("body : " + body);
return body.toString();
}
这会产生以下异常:
org.springframework.web.HttpMediaTypeNotSupportedException: 内容类型'application / json'不是 支持的
如果doSerialize()方法接受String而不是Person,则请求成功,但String为空
答案 0 :(得分:6)
您的jQuery ajax调用会生成以下application/x-www-form-urlencoded
请求正文(以%-decoded格式):
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
s,并将使用字符串索引的属性绑定到Map
s。您需要此处的自定义对象,因为@RequestParam
不支持复杂类型。所以,你有:
public class People {
private List<HashMap<String, String>> people;
... getters, setters ...
}
@RequestMapping("/controllerMethod", method=RequestMethod.POST)
public String doSomething(People people) {
...
}
您也可以在发送数据之前将数据序列化为JSON,然后使用@RequestBody
,如Bozho建议的那样。您可以在mvc-showcase sample中找到此方法的示例。
答案 1 :(得分:3)
如果您启用了<mvc:annotation-driven>
:
@RequestMapping("/controllerMethod", method=RequestMethod.POST)
public String doSomething(@RequestBody List<Person> people) {
System.out.println( wantToSeeListOfPeople );
}
(List<Person>
可能不是您想要获得的结构,这只是一个例子)
您可以尝试将Content-Type
的{{1}}设置为$.ajax
,如果它不能立即生效。
答案 2 :(得分:0)
看看杰克逊的春季整合。它非常易于使用且功能强大。
关于SO的问题/答案可以帮助指导: Spring 3.0 making JSON response using jackson message converter