繁体   English   中英

最佳做法response.getOutputStream

[英]best practice response.getOutputStream

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

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)

异常消息很明确:

无法显示异常页面 :已为此响应调用了getOutputStream()
java.lang.IllegalStateException:已为此响应调用了getOutputStream()
在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 {
        // ???
    }
}

您正在调用response.getOutputStream()两次。 相反,调用它一次并将其分配给局部变量,然后使用该变量进行空检查和write操作。

try {
 OutputStream out = response.getOutputStream();
 if(response !=null && out !=null &&fileObject!=null && fileObject.getBinData() !=null ){
    out.write(fileObject.getBinData());
 }
} catch (IOException e) {
  throw new ApplicationRuntimeException(e);
}

响应如何为空? 特别是在你已经使用它之后? 还是response.getOutputStream()? 或者fileObject,在你已经测试它为非null之后? 用过吗? 这些测试可能弊大于利。

暂无
暂无

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

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