嚴重: Servlet.service() for servlet dispatcherServlet threw exception java.lang.IllegalStateException:

來源:互聯網
上載者:User
嚴重: Servlet.service() for servlet dispatcherServlet threw exception

java.lang.IllegalStateException: getOutputStream() has already been called for this response

at org.apache.catalina.connector.Response.getWriter(Response.java:610)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:198)


這問題困擾了我好久都沒解決,最近這個項目中我又遇到了,下定決心一定要解決掉,這個異常時因為response.getOutputStream()跟response.getWriter()相衝突造成的,也可能是上次使用的資訊未清除,所以需要重設下緩衝。在使用之前加上response.resetBuffer();
現在記錄下,發出來和大家共用下,希望能幫到遇到同樣問題的朋友們,附下代碼:


private HttpServletResponse response;    private String encoding = "UTF-8";    private int blockSize = 1024;    private final Log logger = LogFactory.getLog(getClass());

/** * 輸出資料流到用戶端 * * @param inputStream 輸入資料流 * @param destFileName 另存名 * @throws java.io.IOException */public void write(InputStream inputStream, String destFileName) throws IOException {    this.response.resetBuffer();//重設輸出資料流,清空上次遺留資訊,防止報錯    this.response.setContentType("application/octet-stream");    this.response.setCharacterEncoding(this.encoding);    String downLoad = "";    if (destFileName != null) {        downLoad = new String(destFileName.getBytes("GBK"), "ISO-8859-1");    }    this.response.setHeader("Content-disposition", "attachment;filename=\"" + downLoad + "\"");    OutputStream output = null;    try {        byte[] bytes = new byte[blockSize];        output = this.response.getOutputStream();        int byteRead;        while ((byteRead = inputStream.read(bytes)) != -1) {            output.write(bytes, 0, byteRead);        }        output.flush();    }    catch (Exception ex) {        if (this.response.isCommitted()) {            logger.error("exception class:" + ex.getCause().getClass().getName() + "\nexception message:" + ex.getCause().getMessage());        }        throw new IOException(ex.getMessage());    }    finally {        if (inputStream != null){try{   inputStream.close();}            catch (Exception e) {                logger.error(e.getMessage());            }        }        if (output != null) {            try{                output.close();            }            catch (Exception e) {                logger.error(e.getMessage());            }        }        response.flushBuffer();    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.