【发布时间】:2017-03-20 14:08:45
【问题描述】:
我正在尝试使用 $.ajax 和 @RequestBody,但是当我使用它来传递 Integer 类型时。它无法读取数据并打印null。 @RequestBody可以接收到什么样的数据?
这是我的代码:
var user = {
"username" : "test",
"password" : "test",
"age" : 1
};
$.ajax({
url: "/test1",
type: "POST",
data: JSON.stringify(user),
contentType:"application/json; charset=utf-8",
success: function() {
alert("success")
}
})
这是我的控制器:
@RequestMapping(value = "/test1")
public String test2(@RequestBody User user) {
//Can't receive the Param.
// console result : null
System.out.println(user.getAge());
//Nothing wrong
//console result:
// username: test
// password: test
System.out.println(user.getUsername());
System.out.println(user.getPassword());
return "test";
}
这是用户类:
public class User {
private Integer age;
private String username;
private String password;
//Setting and Getting
}
【问题讨论】:
-
你的 User 类是什么样子的?
-
你的变量名应该和你的模型的字段名一样,在你的json对象中似乎你没有通过
age所以它总是得到null结果 -
在您的代码中,您正在设置 ID 参数,同时打印
user.getAge() -
我已经修改了我的代码并添加了我的 User 类。
标签: json spring spring-mvc controller