I have this problem, I've already asked this question yesterday but i did not have any answer... :(
I have this code on the client-side:
var formdata = new FormData();
//fill fields of formdata... for example:
var file = document.getElementById("file").files[0];
formdata.append("file", file);
//and others....but the problem is not here
var xhr = new XMLHttpRequest();
xhr.open("POST","http://127.0.0.1:8080/Commerciale",true);
xhr.send(formdata);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var str = xhr.responseText;
alert(str);
}
}
});
so far it seems fair. In the servlet I have this code:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
***other code, but i think that the problem is here:
PrintWriter ajaxWriter = response.getWriter();
ajaxWriter.println(p.getJSON());
ajaxWriter.flush();
System.out.println(p.getJSON());
ajaxWriter.close();
}
the problem is that with the
System.out.println(p.getJSON());
prints what I expect, but it seems that
xhr.responseText
does not return anything, in fact, the alert is empty.
someone can explain me why?
:) After discovering that this is the cause:
You should not close the writer after flushing.
Remove the line:
ajaxWriter.close();
An interesting related question - Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()?
Although there is no specific documentation that forbids closing the writer/stream - this is something that the container should perform and not the application.