I've read through all of the Spring 3 Web docs: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/spring-web.html but have been completely unable to find any interesting documentation on binding more complicated request data, for example, let's say I use jQuery to post to a controller like so:
$.ajax({
url: 'controllerMethod',
type: "POST",
data : {
people : [
{
name:"dave",
age:"15"
} ,
{
name:"pete",
age:"12"
} ,
{
name:"steve",
age:"24"
} ]
},
success: function(data) {
alert('done');
}
});
How can I accept that through the controller? Preferably without having to create a custom object, I'd rather just be able to use simple data-types, however if I need custom objects to make things simpler, I'm fine with that too.
To get you started:
@RequestMapping("/controllerMethod", method=RequestMethod.POST)
public String doSomething() {
System.out.println( wantToSeeListOfPeople );
}
Don't worry about the response for this question, all I care about is handling the request, I know how to deal with the responses.
EDIT:
I've got more sample code, but I can't get it to work, what am I missing here?
select 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);
}
});
controller method:
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();
}
this renders the following exception:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported
If the doSerialize() method takes a String as opposed to a Person, the request is successful, but the String is empty