Using Printwriter in servlet response

Victor picture Victor · Oct 25, 2011 · Viewed 37.7k times · Source

In this link it says:Handles the user's request to generate the HTML for the report and writes the HTML directly to the response object. Now in my code, I have:

PrintWriter out = response.getWriter();
crystalReportViewer.processHttpRequest(request, response, context,null);

If I understand correctly, the processHttpRequest will itself do something like response.getWriter().print(.....).

So is the code creating 2 instances of PrintWriter?

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Oct 25, 2011

Response object will return the same writer every time. You can use these writers interchangeably:

final PrintWriter writerA = response.getWriter();
final PrintWriter writerB = response.getWriter();
writerA.println("A1");
writerB.println("B1");
writerA.println("A2");
writerB.println("B2");

The output is as expected because writerA and writerB are actually pointing to the exact same instance of PrintWriter.

I don't know whether it is stated as such in the specification, the Javadoc only says:

Either this method or getOutputStream() may be called to write the body, not both.

That being said your code is not safe for two reasons:

  • crystalReportViewer might call response.getOutputStream() which breaks the contract quoted above

  • if you print something first and then pass the response to the crystalReportViewer chances are your output will break the crystalReportViewer output as it will be prepended.