gpt4 book ai didi

java - 最佳实践 response.getOutputStream

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:34:47 25 4
gpt4 key购买 nike

关于允许用户下载文件的代码的任何评论。

if(fileObject !=null)
response.setHeader("Content-disposition", "attachment; filename=\""+fileObject.getFilename()+"\"");
response.setContentType(fileObject.getFiletype());
response.setContentLength((int)fileObject.getFilesize().intValue());
try {
if(response !=null && response.getOutputStream() !=null &&fileObject!=null && fileObject.getBinData() !=null ){
OutputStream out = response.getOutputStream();
out.write(fileObject.getBinData());
}


} catch (IOException e) {
throw new ApplicationRuntimeException(e);
}

大多数时候,我不会低于错误。但是偶尔,我会出错

29 Nov 2010 10:50:41,925 WARN [http-2020-2] - Unable to present exception page: getOutputStream() has already been called for this response
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:610)

最佳答案

异常信息很明确:

Unable to present exception page: getOutputStream() has already been called for this response
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:610)

IOException 被抛出,您将其作为自定义异常重新抛出,这迫使 servletcontainer 显示将为此使用 getWriter() 的异常页面。事实上,您应该让任何 IOException 消失,因为那通常是不归路。

IOException 例如可以在客户端中止请求时在作业期间抛出。最佳做法是自己在 Servlet API 上捕获 IOException。它已经在 servlet 方法的 throws 子句中声明。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FileObject fileObject = getItSomehow();
if (fileObject != null && fileObject.getBinData() != null) {
response.setHeader("Content-disposition", "attachment; filename=\"" + fileObject.getFilename() + "\"");
response.setContentType(fileObject.getFiletype());
response.setContentLength((int)fileObject.getFilesize().intValue());
response.getOutputStream().write(fileObject.getBinData());
} else {
// ???
}
}

关于java - 最佳实践 response.getOutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4300513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com