控制器中的RequestBody为空

时间:2018-10-30 13:21:36

标签: javascript java jquery ajax spring-mvc

我正在尝试通过jQuery AJAX从前端向后端发送JSON对象。 使用POST方法在请求的路径“ / survey”上成功执行ajax调用。 问题是,我的@RequestBody final HmmSurveyForm hmmSurveyForm的字段“ answer1”和“ heading”具有空值。 当我在Google chrome浏览器中检查请求时,发送了请求:

enter image description here

enter image description here

但是对于前端中填充的字段,响应为null:

enter image description here

我在前端有以下代码:

postSurvey: function() {
        $.ajax({
            url: this.encodedContextPath + "/survey",
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: ACC.hmmSurvey.getJSONDataForSurvey(),
            async: true,
            success: function (response) {
                console.log(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("The following error occurred: " + textStatus, errorThrown);
            }
        });
}

getJSONDataForSurvey: function () {
        var json = [];

        json.push({"answer1": "1"});
        json.push({"heading": "Test"});

        return JSON.stringify({"hmmSurveyForm": json});
}

和后端:

@RequestMapping(value = "/survey", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody HmmSurveyForm postSurvey(@RequestBody final HmmSurveyForm hmmSurveyForm, final Model model) {
    System.out.println(hmmSurveyForm);
    return hmmSurveyForm;
}

public class HmmSurveyForm {

    private String heading;
    private String answer1;

    // getter, setters
}

1 个答案:

答案 0 :(得分:1)

您在JS中错误地声明了RQ正文

var json = [];
json.push({"answer1": "1"});
json.push({"heading": "Test"});
console.log({"hmmSurveyForm": json});

其根hmmSurveyForm是一组不同的对象,与您的后端期望无关。

您应该使用以下代码;

var json = {};
json["answer1"] = "1";
json["heading"] = "Test";
console.log({"hmmSurveyForm": json});

在JS here中查看有关JSON对象的更多信息