java getWriter() 如何在 HttpServletResponse 中起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/750488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does getWriter() function in an HttpServletResponse?
提问by pratap
In the method service(), we use
在方法中service(),我们使用
PrintWriter out = res.getWriter();
Please tell me how it returns the PrintWriterclass object, and then makes a connection to the Browser and sends the data to the Browser.
请告诉我它如何返回PrintWriter类对象,然后连接到浏览器并将数据发送到浏览器。
回答by Jon Skeet
It doesn't makea connection to the browser - the browser has already made a connection to the server. It either buffers what you write in memory, and then transmits the data at the end of the request, or it makes sure all the headers have been written to the network connection and then returns a PrintWriterwhich writes data directly to that network connection.
它不会使浏览器的连接-浏览器已经作出到服务器的连接。它要么缓冲您在内存中写入的内容,然后在请求结束时传输数据,要么确保所有标头都已写入网络连接,然后返回PrintWriter将数据直接写入该网络连接的 a。
In the buffering scenario there may be a fixed buffer size, and if you exceed that the data written so far will be "flushed" to the network connection. The big advantage of having a buffer at all is that if something goes wrong half-way through, you can change your response to an error page. If you've already started writing the response when something goes wrong, there's not a lot you can do to indicate the error cleanly.
在缓冲场景中,可能有一个固定的缓冲区大小,如果超过这个大小,到目前为止写入的数据将“刷新”到网络连接。拥有缓冲区的最大优势在于,如果中途出现问题,您可以更改对错误页面的响应。如果您已经开始在出现问题时编写响应,那么您可以做很多事情来清楚地指出错误。
(There's also the matter of transmitting the content length before any of the content, for keep-alive connections. If you run out of buffer before completing the response, I'm reliably informed that the response will use a chunked encoding.)
(还有在任何内容之前传输内容长度的问题,用于保持活动连接。如果在完成响应之前用完缓冲区,我会可靠地通知响应将使用分块编码。)
回答by Manoj
One fairly simple implementation:
一个相当简单的实现:
PrintWriter getWriter() throws java.io.IOException {
return new PrintWriter(socket.getOutputStream());
}
回答by Thorbj?rn Ravn Andersen
Also note that several open source implementations of the Servlet API is available. This allows you to see how it can be done.
另请注意,有几个 Servlet API 的开源实现可用。这使您可以看到它是如何完成的。
I believe the official implementation has been open sourced too, and is included with the Glassfish server.
我相信官方实现也已经开源,并且包含在 Glassfish 服务器中。

