英文:
Will Print Writer returned by HttpServletResponse use BufferedWriter
问题
我正在开发一个Spring Boot 2.2应用程序,我想要为下载CSV文件公开一个Rest API。我将CSV数据写入HttpServletResponse返回的Writer中。
@RequestMapping(value = "/api", method = RequestMethod.GET)
public void messages(HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
CSVWritter.write(writer, dataService.fetchAllUsers());
writer.flush();
}
根据HttpServletResponse API的Java文档,writer方法将返回PrintWriter。但在Spring Boot中,引用不是PrintWriter类,而是org.springframework.security.web.util.OnCommittedResponseWrapper$SaveContextPrintWriter[delegate=org.apache.catalina.connector.CoyoteWriter@37ef8360]
。
我希望数据被以块的方式写入浏览器,即仅在缓冲区已满时刷新到浏览器。那么,response对象返回的writer是缓冲writer,还是在内部使用了缓冲writer?
英文:
I am working on a spring Boot 2.2 application and I want to expose a Rest API for downloading CSV file.
I am writing my CSV data in a Writer returned by HttpServletResponse.
@RequestMapping(value = "/api", method = RequestMethod.GET)
public void messages(HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
CSVWritter.write(writer, dataService.fetchAllUsers());
writer.flush();
}
As per HttpServletResponse API Java doc writer method will returns PrintWriter. But in Spring boot The reference is not of PrintWriter class instead if it was org.springframework.security.web.util.OnCommittedResponseWrapper$SaveContextPrintWriter[delegate=org.apache.catalina.connector.CoyoteWriter@37ef8360]
I want that data should be written to browser in chunks i.e. it only flushes to browser when buffer is full. So The writer returned by response object is Buffered writer or is it using buffered writer internally?
答案1
得分: 0
ServletResponse文档没有明确说明,但flushBuffer()
、getBufferSize()
和setBufferSize()
方法的存在强烈暗示输出流/写入器确实是有缓冲的。
从实际情况来看,必须这样做才能设置Content-Length
(或支持分块编码,其中内容长度不是预先已知的)。
注:PrintWriter
是一个装饰器;它本身没有内部缓冲,但可以装饰一个有缓冲的写入器。其文档中对“刷新”(flushing)的引用与装饰的Writer
在每次写入后是否显式调用flush()
有关。
英文:
The ServletResponse docs aren't explicit, but the presence of the methods flushBuffer()
, getBufferSize()
, and setBufferSize()
strongly imply that the output stream/writer is indeed buffered.
As a practical matter it has to be, to set Content-Length
(or support chunked encoding, where content-length isn't known up-front).
NB: PrintWriter
is a decorator; it is not internally buffered, but may decorate a writer that is buffered. The references to "flushing" in its docs relate to whether it explicitly calls flush()
on the decorated Writer
after every write.
专注分享java语言的经验与见解,让所有开发者获益!
评论