如何从Javascript调用Spring MVC?

时间:2012-06-13 13:13:43

标签: jquery spring-mvc

如何从请求参数中实例化自定义对象? (我已经尝试了@ModelAttribute和@RequestParam)

@RequestMapping(method = RequestMethod.POST)
public String newPerson(@ModelAttribute(value = "personModel") 
                          Person person, BindingResult result) {
// Person has just firstname and lastname fields
 }

我尝试使用以下代码使用jQuery调用它:

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);
}
});

事实上,我最初的计划是将整个人物对象列表发送到控制器,但由于这不起作用,我还原为单个对象,但现在这也不起作用。

编辑:param不一定是JSON,我只是认为将Javascript对象序列化为JSON到Spring Controller是有意义的。

2 个答案:

答案 0 :(得分:0)

我能够通过Javascript(jquery)

进行以下调用
$.post("/modifylist.do",{ firstname: "John", lastname: "Doe" } );

但是,我仍然非常想知道如何使用数组或列表,即参数为Person[]List<Person>

答案 1 :(得分:0)

@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
 }

你可以像这样使用它。对于列表,您可以使用以下内容:

Gson gson = new Gson();
List<Person> finalObjectList = gson.fromJson(Person, new TypeToken<List<Person>>() {
    }.getType());

我希望能帮到你:)。