无法将 Json 数据从 Ajax 发送到 Servlet

Unable to send Json data from Ajax to Servlet

我正在尝试使用 Ajax 从 JavaScript 函数向 Servlet 发送 JSON 数据。

客户端:

function addObject() {
    var data = {
        aa: "aa",
        bb: "bb"
    }
    var string = JSON.stringify(data);
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "GalleryAdd", true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            console.log("Done");
        }
    };
    console.log(string);
    xhttp.send(string);
}

字符串化数据的输出是 {"aa":"aa","bb":"bb"}

Servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    log(request.getParameter("aa"));
    log(request.getParameter("bb"));
}

记录器中的输出是 nullnull

看起来 JavaScript 没有向 servlet 发送数据,如果它的字符串化正确的话。有人吗?

您的 Json 对象在请求的正文中,因此您需要解析 InputStream。试试这个。

protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    JsonObject object = Json.createReader(req.getInputStream()).readObject();

    log(object.getString("aa"));
    log(object.getString("bb"));
}