Good evening, i want to know how to clear the data written to a PrintWriter, i.e. is it possible to remove the data from a PrintWriter after printing?
here in this servlet i print some text to the response and at the line denoted by # i want to remove all the previously printed data and print new stuff:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String uName = request.getParameter("uName");
String uPassword = request.getParameter("uPassword");
if (uName .equals("Islam")) {
out.println("Valid-Name");
if (uPassword !=null) {
if (uPassword .equals("Islam")) {
// # clear the writer from any printed data here
out.println("Valid-password");
} else {
out.println("");
out.println("InValid-password");
}
}
} else {
out.println("InValid-Name");
}
}
Note: i tried out.flush() but the old printed text remains
You can't do that with the original
PrintWriter
you get from the response, as that's backed by the actualOutputStream
corresponding to the client connection. What you write there goes right to the browser via the wire (after some buffering), so you can't "take it back".What you can do is write your message in some
StringBuilder
and once you know it's good to go, write it to thePrintWriter
.If you want this logic to be applied in multiple places (transparently), you can consider writing a filter that wraps the original response in an
HttpServletResponseWrapper
which returns a "fake"OutputStream
orPrintWriter
and performs this check prior to actually sending it over the wire.What ended up working for me was to change the logic of how I was outputting my data.
This is the data structure I was outputting that stored the results of a search using the text from a html form as input.
So I was iterating over the contents of this data structure and printing it out to html.
Clearing the data structure worked great given my servlet setup.
Here was my main serverlet loop logic:
HttpServlteResponse.resetBuffer()
will clear the buffered content. But yes, if the response is already flushed to the client it will throwIllegalStateException
. Because it is illegal to clear after partial response is sent to the client.References:
Cause of Servlet's 'Response Already Committed'
Create an in-memory
PrintWriter
using aStringWriter
. You can get the underlying buffer from theStringWriter
and clear it if you need to.