java - Spring MVC - 将 JSON 对象从 Ajax post 请求映射到 Java 对象

标签 java jquery ajax json spring

我正在尝试发出 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/

相关文章:

jquery - 如何修复 Google Chrome 移动加载页面上的黑屏

javascript - 将类名从 div 移动到 div

java - 如何在 Openshift Origin PAAS 上设置 Java 堆大小

java从文件夹加载文件,但项目是一个模块

javascript - jQuery 每个只影响最后一项

javascript - Ajax调用后数据为空如何比较记录数?

ajax - 使用对象中的更改更新 DOM (vue.js) - 绑定(bind)不起作用?

javascript - jquery自动完成显示div内返回的html结果

java - 0.99999999999相乘时可以四舍五入到1.0吗?

java - 复制二进制文件会将换行符更改为窗口标准..? java