加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 最佳实践response.getOutputStream

发布时间:2020-12-15 08:36:42 所属栏目:Java 来源:网络整理
导读:允许用户下载文件的任何关于我的代码的评论. if(fileObject !=null)response.setHeader("Content-disposition","attachment; filename=""+fileObject.getFilename()+""");response.setContentType(fileObject.getFiletype());response.setContentLength((i
允许用户下载文件的任何关于我的代码的评论.

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 {
        // ???
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读