如何从Javascript调用Spring MVC? [英] How to call Spring MVC from Javascript?
问题描述
如何从请求参数中实例化自定义对象? (我已经尝试过@ModelAttribute和@RequestParam)
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
}
我尝试使用以下代码使用jQuery进行调用:
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.
参数不必是JSON,我只是认为将Javascript对象作为JSON序列化到Spring Controller上是有意义的.
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.
推荐答案
@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());
希望对您有所帮助:)
这篇关于如何从Javascript调用Spring MVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!