How to pass a text response with Java Spring MVC 3.0 Webapp

How can I send text output to a browser page to show the progress of an operation, which can take about 15-20 seconds? I tried to directly write the HttpServletResponse output stream, but the user still sees the full output after the completion of the whole process.

This is what I have 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(); } 
+6
source share
3 answers

I am not an expert at MVC Spring, but I would think that you would do something like send a response code of "accepted" 202, which indicates that the server has received the request and is about to perform some asynchronous processing. Typically, the server provides a URL that allows the client to query the status of the operation. What you are trying to do violates the usual way of communication between the server and the client. The client calls the server and the server responds, and then the connection closes. In what context are you trying to do this and for what reason? Perhaps I could offer a deeper understanding or think of another way to do this?

+1
source

try using:

 response.flushBuffer(); 

as JavaDoc says:

Causes any content in the buffer to be written to the client. A call to this method automatically transmits a response, that is, a status code and headers will be recorded.

+1
source
 @Controller public class MyController{ @RequestMapping(value = "/test", method = RequestMethod.GET) public @ResponseBody String getTest() { return "hello how are you"; } } 

If you use a spring controller, you can do this with annotation of the response body.

-4
source

Source: https://habr.com/ru/post/919769/


All Articles