I have a tomcat6 servlet that manages incoming HttpPosts this way:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("cmd") != null) {
eventPool.addEvent(new CommandEvent(new String[] { request.getParameter("cmd"),
request.getParameter("json") }, response));
}
}
The request will now be processed. When this is done, I want to write the result to the requesting client this way:
protected void sendResponse(HttpServletResponse httpResponse, String content){
try {
httpResponse.getWriter().println(CMD + "#" + content);
httpResponse.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
But it fails to flush and I get a NullPointerException because the HttpResponse was already closed.
How can I prevent the HttpResponse from flushing before I want it to?
You’ll need to use Tomcat 7 (or any other container that supports Servlet 3.0 onwards) to use that style of programming. Look at the asynchronous request processing parts of the Servlet 3.0 specification.
Prior to Servlet 3.0, request/response processing is synchronous. i.e. you cannot ‘park’ a request/response pair and then handle them later in a different thread. Pretty much as soon as your doPost() method exits, Tomcat will recycle the request and response objects ready to use them to handle a new request.