简体   繁体   English

RequestBody 在控制器中为空

[英]RequestBody is null in controller

I'm trying to send JSON object from frontend to backend via jQuery AJAX.我正在尝试通过 jQuery AJAX 将 JSON 对象从前端发送到后端。 The ajax call is performed successfully on the requested path "/survey" with a POST method.使用 POST 方法在请求的路径“/survey”上成功执行了 ajax 调用。 Problem is, my @RequestBody final HmmSurveyForm hmmSurveyForm has null values for my fields "answer1" and "heading".问题是,我的@RequestBody final HmmSurveyForm hmmSurveyForm字段“answer1”和“heading”为空值。 When I checked request in google chrome developer request is sent:当我检查谷歌浏览器中的请求时,开发者请求被发送:

在此处输入图片说明

在此处输入图片说明

But the response is null for populated fields from frontend:但是对于来自前端的填充字段,响应为空:

在此处输入图片说明

I have following code in frontend:我在前端有以下代码:

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});
}

and in backend:并在后端:

@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
}

You are declaring your RQ body incorrectly in JS您在 JS 中错误地声明了您的 RQ 主体

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

which has the root hmmSurveyForm as an array of distinct objects, which has no relation to what your backend expects.它的根hmmSurveyForm作为一个不同对象的数组,与您的后端期望无关。

You should be using the code below;您应该使用下面的代码;

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

Check more on JSON Object in JS here此处查看有关 JS 中的 JSON 对象的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM