Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Stream Text Response From a Java Spring MVC 3.0 Webapp

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();
}
like image 413
Danish Avatar asked Jul 05 '12 14:07

Danish


2 Answers

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?

like image 85
thatidiotguy Avatar answered Sep 20 '22 21:09

thatidiotguy


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.

like image 42
user1335851 Avatar answered Sep 22 '22 21:09

user1335851