How to clear Java screen output HttpServletResponse

I am writing to a browser window using servletResponse.getWriter (). write (String).

But how to clear the text that was written earlier by some other similar record call?

+3
source share
4 answers

Short answer: you cannot - as soon as the browser receives a response, there is no way to return it. (If there is some possibility of abnormally stopping the HTTP response to force the client to reload the page or something like that.)

Probably the last place the answer can be "cleared" in a sense, uses a method ServletResponse.resetthat, according to the Servlet Specification , will reset the servlet's response buffer.

, , (.. ) ServletOutputStream flush.

+4

. (StringWriter/StringBuilder), . , , .

, , JSP, Velocity, FreeMarker ..

+2

, , , - , , . , , , .

. , , , . , - . , , -, . . ORM Entity - ! , 3/4 .

, - AJAX. - ?

!

+1

, , , .

, Filter ServletResponseWrapper, .

, - ... , , , , .

,

public class MyResponseWrapper extends HttpServletResponseWrapper {
    protected ByteArrayOutputStream baos = null;
    protected ServletOutputStream stream = null;
    protected PrintWriter writer = null;
    protected HttpServletResponse origResponse = null;

    public MyResponseWrapper( HttpServletResponse response ) {
      super( response );
      origResponse = response;
    }


    public ServletOutputStream getOutputStream()
      throws IOException {
      if( writer != null ) {
        throw new IllegalStateException( "getWriter() has already been " +
                                   "called for this response" );
      }

      if( stream == null ) {
        baos = new ByteArrayOutputStream();
        stream = new MyServletStream(baos);
      }

      return stream;
    }

  public PrintWriter getWriter()
    throws IOException {
      if( writer != null ) {
        return writer;
      }

      if( stream != null ) {
        throw new IllegalStateException( "getOutputStream() has already " +
                                   "been called for this response" );
      }

      baos = new ByteArrayOutputStream();
      stream = new MyServletStream(baos);
      writer = new PrintWriter( stream );

      return writer;
    }

    public void commitToResponse() {
      origResponse.getOutputStream().write(baos.toByteArray());
      origResponse.flush();
    }

    private static class MyServletStream extends ServletOutputStream {
       ByteArrayOutputStream baos;

       MyServletStream(ByteArrayOutputStream baos) {
         this.baos = baos;
       }

       public void write(int param) throws IOException {
         baos.write(param);
       }
    }
    //other methods you want to implement
  }
0

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


All Articles