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

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

你可能感兴趣的:(JavaEE-综合,JavaEE-Web前台,Java-综合)