How to call Spring MVC from Javascript?

亡梦爱人 提交于 2020-01-25 20:22:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!