【发布时间】:2015-08-09 00:23:40
【问题描述】:
我正在尝试发出 AJAX 发布请求,但我的 JSON 对象值没有从我的控制器映射到 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
类型 = 空
金额 = 0.0
我也尝试在控制器方法中将@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)
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
它是不是 Spring Boot 应用程序?
-
嗨,我是 Spring 新手——我认为我没有使用 Spring Boot。我在 Tomcat 上运行我的应用程序。
-
好的,我想你必须配置一个 ObjectMapper。 (当你使用 Spring Boot 时,它和许多其他东西都会自动配置,我认为使用 Spring Boot 是学习 Spring 的更好方法,而不是不使用它)
-
在 $.ajax 调用之前尝试 console.log(account),检查浏览器控制台是否有数据正在传递给 java。
-
是的,账户 JSON 对象在控制台中打印出来
标签: java jquery ajax json spring