当前位置: 首页 > 知识库问答 >
问题:

IllegalStateException:已经为此响应调用了getOutputStream()[重复]

雷曜灿
2023-03-14

最大的问题是,对于以下异常,代码片段可以正常工作。用户可以将文档保存在所需的位置。我想弄清楚为什么我会得到这个错误。

java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:611)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:198)
t  DownloadServlet.doGet(DownloadServlet.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
 getDocument(HttpServletRequest request,HttpServletResponse response)
   {
 \\used Custom web services methods to get filename with extensions from external ECM system 
   File resultFile = content.getAsFile();
   response.setContentType("application/octet-stream");  
   ServletOutputStream outStream = response.getOutputStream();          
   try {
       response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
       byte[] byteBuffer = new byte[BUFSIZE];
       DataInputStream in = new DataInputStream(new FileInputStream(file));
          while ((in != null) && ((length = in.read(byteBuffer)) != -1)){
            outStream.write(byteBuffer,0,length);
            }
            in.close();
            outStream.flush();                              
      } catch (Exception e) {
          e.printStackTrace();
      }finally{
          outStream.close();
      }

 }

共有1个答案

秦飞航
2023-03-14

我在使用Struts2框架工作时也遇到了同样的问题。我找了一段时间,我找到的解决办法对我有效。我在某个地方发现:

HTTP的基本规则:一个请求,一个响应。您只能向请求发回一件东西。如果您已经获得了Writer/OutputStream,那么Java会抱怨HTML页面、PDF文档或图像等,因为您应该只获得其中一个Writer/OutputStream。

在我的例子中,下载文件的action类在文件下载后向请求返回字符串“sucess”,这导致了问题。我将方法的返回类型更改为void和issue resolved。

 类似资料: