简体   繁体   English

在Servlet响应中使用Printwriter

[英]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. 在此链接中表示:处理用户的请求以生成报告的HTML,并将HTML直接写入响应对象。 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(.....). 如果我理解正确, processHttpRequest本身将执行诸如response.getWriter().print(.....).

So is the code creating 2 instances of PrintWriter ? 那么,代码是否将创建两个PrintWriter实例?

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 . 输出是预期的,因为writerAwriterB实际上指向完全相同的PrintWriter实例。

I don't know whether it is stated as such in the specification, the Javadoc only says: 我不知道规范中是否这样声明, Javadoc只说:

Either this method or getOutputStream() may be called to write the body, not both. 可以调用此方法或getOutputStream()来编写主体,但不能同时调用两者。

That being said your code is not safe for two reasons: 话虽如此,您的代码并不安全,原因有两个:

  • crystalReportViewer might call response.getOutputStream() which breaks the contract quoted above crystalReportViewer可能会调用response.getOutputStream() ,这会破坏上面引用的合同

  • 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. 如果您先打印某些内容,然后将response传递给crystalReportViewer则您的输出可能会破坏crystalReportViewer输出,因为它将被前置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM