问题
How do you instantiate a custom object from a request param? (I have tried both @ModelAttribute and @RequestParam)
@RequestMapping(method = RequestMethod.POST)
public String newPerson(@ModelAttribute(value = "personModel")
Person person, BindingResult result) {
// Person has just firstname and lastname fields
}
I try to call this with jQuery using the following code:
var PersonText = '["firstname":"John", "lastname":"Someone"]';
$.ajax({
type : 'POST',
url : "/addnewperson.do",
data : {'personModel' : personText},
datatype : 'json',
success : function(data) {
var obj = jQuery.parseJSON(data);
}
});
In fact my original plan was to send an entire list of person objects over to the controller, but since that didn't work I reverted back to a single object, but now that doesn't work either.
EDIT: the param doesn't have to be JSON, I just thought it would make sense to serialize the Javascript object as JSON over to the Spring Controller.
回答1:
I was able to get this to work with the following call from Javascript (jquery)
$.post("/modifylist.do",{ firstname: "John", lastname: "Doe" } );
However, I'd still really like to know how to get this to work with arrays or lists, i.e. the parameter being Person[] or List<Person> instead.
回答2:
@RequestMapping(method = RequestMethod.POST)
public String newPerson(@RequestParam("personModel") String person, BindingResult result) {
Gson gson = new Gson();
Person finalObject = gson.fromJson(person, Person.class);
// Person has just firstname and lastname fields
}
You can use it like this. and for list you can use something like :
Gson gson = new Gson();
List<Person> finalObjectList = gson.fromJson(Person, new TypeToken<List<Person>>() {
}.getType());
I hope that helps you :)
来源:https://stackoverflow.com/questions/11015611/how-to-call-spring-mvc-from-javascript