2010-11-29 161 views
3

對我的代碼允許用戶下載文件的任何評論。最佳做法response.getOutputStream

if(fileObject !=null) 
response.setHeader("Content-disposition", "attachment; filename=\""+fileObject.getFilename()+"\""); 
response.setContentType(fileObject.getFiletype()); 
response.setContentLength((int)fileObject.getFilesize().intValue()); 
try { 
if(response !=null && response.getOutputStream() !=null &&fileObject!=null && fileObject.getBinData() !=null){ 
    OutputStream out = response.getOutputStream(); 
    out.write(fileObject.getBinData()); 
} 


} catch (IOException e) { 
    throw new ApplicationRuntimeException(e); 
} 

大多數時候,我沒有得到低於錯誤。但有一次,我得到錯誤

29 Nov 2010 10:50:41,925 WARN [http-2020-2] - Unable to present exception page: getOutputStream() has already been called for this response 
java.lang.IllegalStateException: getOutputStream() has already been called for this response 
at org.apache.catalina.connector.Response.getWriter(Response.java:610) 
+0

您聲明這與tapestry有關,但是在您的問題中沒有提及任何tapestry。請解釋這是如何掛毯相關或刪除標籤。 – pstanton 2010-11-29 04:04:45

+0

掛毯服務 – cometta 2010-11-29 04:06:46

回答

4

異常信息是明確的:

無法呈現異常頁面:的getOutputStream()有已被調用此響應
java.lang.IllegalStateException:getOutputStream()已被調用此響應
at org.apache.catalina.connector.Response。 的getWriter(Response.java:610)

IOException是被拋出你重新拋出它作爲迫使servletcontainer表明將使用getWriter()這個異常頁面自定義異常。你應該讓任何IOException去,因爲這通常是一個不歸路。

例如,當客戶端中止請求時,可以在作業期間拋出IOException。最佳做法是自己對而不是捕獲IOException關於Servlet API。它已經在servlet方法的throws子句中聲明。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    FileObject fileObject = getItSomehow(); 
    if (fileObject != null && fileObject.getBinData() != null) { 
     response.setHeader("Content-disposition", "attachment; filename=\"" + fileObject.getFilename() + "\""); 
     response.setContentType(fileObject.getFiletype()); 
     response.setContentLength((int)fileObject.getFilesize().intValue()); 
     response.getOutputStream().write(fileObject.getBinData()); 
    } else { 
     // ??? 
    } 
} 
3

您正在撥打response.getOutputStream()兩次。相反,調用一次並將其分配給本地變量,然後使用該變量進行空檢查和您的操作。

try { 
OutputStream out = response.getOutputStream(); 
if(response !=null && out !=null &&fileObject!=null && fileObject.getBinData() !=null){ 
    out.write(fileObject.getBinData()); 
} 
} catch (IOException e) { 
    throw new ApplicationRuntimeException(e); 
} 
+3

這不是問題的原因。您可以隨意調用`getOutputStream()`和`getWriter()`多次,但** * * * * * * * * *都不是* * *。 – BalusC 2010-11-29 03:13:24

0

答案如何爲空?特別是在你已經使用它之後?或者response.getOutputStream()?或fileObject,你已經測試它爲非空嗎?並用它?這些測試可能會造成更多的傷害。