How can I stream text output to the page on the browser to show the progress of an operation that may take about 15 - 20 seconds? I've tried writing to the output stream of HttpServletResponse
directly, but the user still sees the full output after the whole process is finished.
This is what I've tried so far
@RequestMapping(value = "/test")
public void test(HttpServletResponse response)
throws IOException, InterruptedException {
response.getOutputStream().println("Hello");
response.getOutputStream().flush();
Thread.sleep(2000);
response.getOutputStream().println("How");
response.getOutputStream().flush();
Thread.sleep(2000);
response.getOutputStream().println("are");
response.getOutputStream().flush();
Thread.sleep(2000);
response.getOutputStream().println("you");
response.getOutputStream().flush();
}
I am no Spring MVC expert, but I would think you would do something like send a 202 response code of "accepted", which indicates the server has received the request and is going to do some asynchronous processing. Usually, the server provides a URL to allow the client to issue requests about the status of the operation. What you are trying to do violates the usual way server/client relationships work. The client calls the server, and the server responds and then the connection is closed. In what context are you trying to do this and for what reason? Perhaps I could offer some more insight or think of another way to do it?
try to use:
response.flushBuffer();
as JavaDoc says:
Forces any content in the buffer to be written to the client. A call to this method automatically commits the response, meaning the status code and headers will be written.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With