繁体   English   中英

在Servlet响应中使用Printwriter

[英]Using Printwriter in servlet response

在此链接中表示:处理用户的请求以生成报告的HTML,并将HTML直接写入响应对象。 现在在我的代码中,我有:

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

如果我理解正确, processHttpRequest本身将执行诸如response.getWriter().print(.....).

那么,代码是否将创建两个PrintWriter实例?

响应对象每次都会返回相同的编写器。 您可以互换使用这些编写器:

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

输出是预期的,因为writerAwriterB实际上指向完全相同的PrintWriter实例。

我不知道规范中是否这样声明, Javadoc只说:

可以调用此方法或getOutputStream()来编写主体,但不能同时调用两者。

话虽如此,您的代码并不安全,原因有两个:

  • crystalReportViewer可能会调用response.getOutputStream() ,这会破坏上面引用的合同

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

暂无
暂无

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

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