Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Printwriter in servlet response

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?

like image 601
Victor Avatar asked Oct 25 '11 15:10

Victor


People also ask

What is the use of PrintWriter out response getWriter ()?

getWriter. Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding() .

How do you perform the dynamic interception of requests and responses?

How is the dynamic interception of requests and responses to transform the information done? Explanation: Servlet has various components like container, config, context, filter. Servlet filter provides the dynamic interception of requests and responses to transform the information.

What does PrintWriter do in Java?

“PrintWriter is a class used to write any form of data e.g. int, float, double, String or Object in the form of text either on the console or in a file in Java.” For example, you may use the PrintWriter object to log data in a file or print it on the console.


1 Answers

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.

like image 144
Tomasz Nurkiewicz Avatar answered Oct 16 '22 15:10

Tomasz Nurkiewicz