Issue
I'm trying to send JSON data from a JavaScript function using Ajax to a Servlet.
Client side:
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);
}
Output from stringyfied data is {"aa":"aa","bb":"bb"}
.
Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
log(request.getParameter("aa"));
log(request.getParameter("bb"));
}
Output in the logger is null
and null
.
Looks like JavaScript does not send data to the servlet, also if it's stringifyed correctly. Anyone?
Solution
Your Json object is in the body of the request therefore you need to parse the InputStream
. Try this.
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
JsonObject object = Json.createReader(req.getInputStream()).readObject();
log(object.getString("aa"));
log(object.getString("bb"));
}
Answered By - chriptus13