[英]best practice 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)
異常消息很明確:
無法顯示異常頁面 :已為此響應調用了getOutputStream()
java.lang.IllegalStateException:已為此響應調用了getOutputStream()
在org.apache.catalina.connector.Response。 getWriter (Response.java:610)
拋出了IOException
並且您將其重新拋出為自定義異常,這迫使servletcontainer顯示將使用getWriter()
的異常頁面。 實際上你應該讓任何IOException
出現,因為這通常是一個不歸路。
例如,當客戶端中止請求時,可以在作業期間拋出IOException
。 最佳做法是不要自己捕獲Servlet API上的IOException
。 它已經在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 {
// ???
}
}
您正在調用response.getOutputStream()
兩次。 相反,調用它一次並將其分配給局部變量,然后使用該變量進行空檢查和write
操作。
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);
}
響應如何為空? 特別是在你已經使用它之后? 還是response.getOutputStream()? 或者fileObject,在你已經測試它為非null之后? 用過嗎? 這些測試可能弊大於利。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.