簡體   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