我正在尝试发出 AJAX post 请求,但我的 JSON 对象值未映射到 Controller 中的 Java 对象。当我调试 Java 对象字段时,我得到返回的空值。请参阅下面的代码。
AJAX 请求
$('#form').submit(function(e) {
e.preventDefault();
var account = {};
account.type = $('#account-type option:selected').text();
account.name = $('#account-names option:selected').text();
account.amount = $(this).find('input[name=amount]').val();
$.ajax({
contentType: 'application/json',
url: '/spring-mvc-practice/account/create',
type: 'POST',
dataType: 'json',
data: JSON.stringify(account),
success: function(response) {
console.log("success");
},
error: function() {
console.log("error");
}
});
});
AccountController.java
@Controller
public class AccountController {
@RequestMapping(value = "/account/create", method = RequestMethod.POST, headers = {"Content-type=application/json"})
@ResponseBody
public String createAccount(@ModelAttribute Account account) {
System.out.println("name = " + account.getName());
System.out.println("type = " + account.getType());
System.out.println("amount = " + account.getAmount());
return null;
}
}
帐户.java
public class Account {
private String name;
private String type;
private double amount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
调试结果:
name = null
type = null
amount = 0.0
我还尝试在 Controller 方法中将 @ModelAttribute
更改为 @RequestBody
(根据本教程: https://gerrydevstory.com/2013/08/14/posting-json-to-spring-mvc-controller/ ),但是当我执行以下操作时出现此错误AJAX 请求:
POST http://localhost:8080/spring-mvc-practice/account/create 415 (Unsupported Media Type)
任何帮助将不胜感激。谢谢。
最佳答案
如果您想使用@RequestBody
,只需将您的createAccount
方法替换为:
@ResponseBody
@RequestMapping(value = "/account/create", method = RequestMethod.POST)
public String createAccount(@RequestBody final Account account) {
System.out.println("name = " + account.getName());
System.out.println("type = " + account.getType());
System.out.println("amount = " + account.getAmount());
return null;
}
...您的 AJAX 调用应该具有:
$.ajax({
contentType: 'application/json;charset=UTF-8',
url: '/spring-mvc-practice/account/create',
dataType: 'json',
type: 'POST',
cache: false, // Force requested pages not to be cached by the browser
processData: false, // Avoid making query string instead of JSON
data: JSON.stringify(account)
}).done(function (data) {
console.log('AJAX call was successfully executed ;)');
console.log('data = ', data);
}).fail(function () {
console.log('AJAX call failed :(');
});
...最重要的是,您的类路径中必须具有此依赖项(您可以使用这些版本,以防万一您不能特别拥有该版本...请注意,我正在使用 Maven):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.0</version>
</dependency>
关于java - Spring MVC - 将 JSON 对象从 Ajax post 请求映射到 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31899843/