【问题标题】:Spring MVC - Mapping JSON object from Ajax post request to Java objectSpring MVC - 将 JSON 对象从 Ajax 发布请求映射到 Java 对象
【发布时间】: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


【解决方案1】:

如果您想使用 @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>

【讨论】:

  • 我用你那里的代码替换了我的代码,还添加了依赖项,但是当我执行 AJAX 请求时出现此错误:POST localhost:8080/spring-mvc-practice/account/create 415 (Unsupported Media Type)
  • @DavidFoster 这意味着您不能将Account 序列化为 JSON;仔细检查您的类路径中有jackson-databind。你在使用 Maven 吗?另外,您使用的是什么版本的 Spring?
  • 我使用的是 Maven,jackson-databind jar 与我的其他 Spring jar 位于同一个 lib 文件夹中。我正在使用 Spring 4.1.7 版
  • @DavidFoster 在 Maven 的项目中没有 /lib 文件夹...除非您在讨论生成的 WAR/EAR 文件中的 /lib 文件夹
  • 是的,WAR里面的/lib文件夹
【解决方案2】:

请尝试分配您的参数帐户以通过类似的方式传递。从现在开始,您将它们作为数组传递,该数组主要用于传递列表。因此,例如,您想要列出帐户,那么您将使用上面的语法。

但是现在请试试这个:

var account = {type: $('#account-type option:selected').text(),name: $('#account-names option:selected').text(),amount : $(this).find('input[name=amount]').val()};

【讨论】:

  • 还是不行。我的 Java 对象中仍然有空值。
  • @David 您是否从浏览器开发工具中检查过发送的请求是什么?在网络选项卡中,您可以看到它发布到控制器的 json 字符串是什么。
  • 尝试将内容类型设置为 contentType: "application/json;charset=utf-8",
  • 在network选项卡中,我看到Request Payload中的json {type: "Savings", name: "Savings Account", amount: "23123"}
  • @David 尝试保留 contentType: "application/json" remove charset = utf-8
猜你喜欢
  • 1970-01-01
  • 2013-12-02
  • 2012-06-26
  • 2014-12-08
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
相关资源
最近更新 更多