java.lang.IllegalStateException: getOutputStream() has already been called for this response
分享| 2015-01-05 16:30 139****9232 | 瀏覽 1047 次
BufferedInputStream in = null;
BufferedOutputStream out = null;
if (printFile == null) {
throw new WebException("傳入參數printFile文件爲空!");
}
try {
in = new BufferedInputStream(new FileInputStream(printFile
.getPath()));
if (printFile.getName().substring(
printFile.getName().lastIndexOf(".")).equals(".xls")) {
response.setContentType("application/vnd.ms-excel");
filename = new String(filename
.getBytes("GBK"), "ISO8859_1").trim()+".xls";
response.setHeader("Content-Disposition", streamType
+ ";filename=" + filename);
}
out = new BufferedOutputStream(response.getOutputStream());
byte[] buf = new byte[1024];
while ((in.read(buf)) > 0) {
out.write(buf);
}
out.flush();
} catch (IOException e) {
throw new WebException("生成response出錯!", e);
} catch (Exception e) {
throw new WebException("生成response出錯!", e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
System.out.print("ouputStream.close() fail");
}
}
if (out != null) {
try {
out.close();
} catch (IOException ex) {
System.out.print("baos.close() fail");
}
}
if(printFile!=null){
printFile.delete();
}
}
2015-01-05 19:54 網友採納
我想知道這個方法執行完之後,有沒有進行請求轉發,這個錯誤通常是伴隨在請求轉發時發生的。---------------------------------------------------------------------------------------------------------------------如下是我總結的有關Response對象字節流與請求轉發之間的異常說明。只供參考!狀況1: 得到響應對象的字節流response.getOutputStream(),可是不進行任何的操做,也不調用其close()方法,此時,在進行請求轉發時,會轉發成功。可是在轉發到的jsp頁面時,會得到其response的字符流,此時由於response已經得到了其字節流,因此會出現如下異常:getOutputStream() has already been called for this response! 狀況2: 得到響應對象的字節流response.getOutputStream(),可是不進行任何的操做,可是調用了該字節流的close()方法,此時,在進行請求轉發時,不會成功。 由於請求轉發器會判斷response的字節流是否已提交,若是已提交,則會出現如下異常: Cannot forward after response has been committed!結論:在整個請求過程當中,若是須要進行請求轉發,則不可以得到響應對象的字節流!response.getOutputStream()