嚴重: 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(); }}