Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the screen output of a Java HttpServletResponse

Tags:

java

servlets

I'm writing to the browser window using servletResponse.getWriter().write(String).

But how do I clear the text which was written previously by some other similar write call?

like image 946
n1kh1lp Avatar asked Dec 08 '25 10:12

n1kh1lp


2 Answers

The short answer is, you cannot -- once the browser receives the response, there is no way to take it back. (Unless there is some way to abnormally stop a HTTP response to cause the client to reload the page, or something to that extent.)

Probably the last place a response can be "cleared" in a sense, is using the ServletResponse.reset method, which according to the Servlet Specification, will reset the buffer of the servlet's response.

However, this method also seems to have a catch, as it will only work if the buffer has not been committed (i.e. sent to the client) by the ServletOutputStream's flush method.

like image 54
coobird Avatar answered Dec 09 '25 22:12

coobird


You cannot. The best thing is to write to a buffer (StringWriter / StringBuilder) and then you can replace the written data any time. Only when you know for sure what is the response you can write the buffer's content to the response.

In the same matter, and reason to write the response this way and not to use some view technology for your output such as JSP, Velocity, FreeMarker, etc.?

like image 44
David Rabinowitz Avatar answered Dec 09 '25 22:12

David Rabinowitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!