getOutputStream() has already been called for this response問題的解決
tomcat5下jsp出現getOutputStream() has already been called for this response異常的原因和解決方法
在tomcat5下jsp中出現此錯誤一般都是在jsp中使用了輸出流(如輸出圖片驗證碼,檔案下載等),
沒有妥善處理好的原因。
具體的原因就是
在tomcat中jsp編譯成servlet之後在函式_jspService(HttpServletRequest request, HttpServletResponse response)的最後
有一段這樣的程式碼
finally {
if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
}
這裡是在釋放在jsp中使用的物件,會呼叫response.getWriter(),因為這個方法是和
response.getOutputStream()相沖突的!所以會出現以上這個異常。
採用方法很簡單.在使用OutputStream輸出流完成後,呼叫下面2個方法即可解決該問題:
out.clear();
out = pageContext.pushBody();
示例程式碼:
OutputStream os=response.getOutputStream();
os.write(new String("true "+"nowNum=" + nowNum+"===").getBytes());
os.flush();
os.close();
out.clear();
out = pageContext.pushBody();
還有以下方法
解決方法是捕獲異常,程式碼如下:
java 程式碼
try {
............
} catch (RuntimeException e) {
e.printStackTrace();
}
如果還出現錯誤,可以用以下方法解決:
如果是在jsp頁面,使用以下程式碼:
out.clear();
out=pageContext.pushBody();
//清除緩衝區中的內容,不將資料傳送至客戶端。
如果寫成一個類的話,在產生驗證碼的方法裡面,呼叫pageContext引數,在jsp裡面,它是一個物件,因此在呼叫引數時加上型別Page(大寫),引入的包為import javax.servlet.jsp.*(eclipse自帶);
因此在java類裡程式碼如下:
JspWriter out=page.getOut();//此處的out屬於import javax.servlet.jsp.JspWriter方法的例項。
out.clear();
out=page.pushBody();
response.flushBuffer();
另外PageContex與ServletContext是不同的,PageContext就是JSP中的page,ServletContext就是JSP中的application,兩者的scope不一樣。
以上是我的一些想法,如有錯誤,歡迎回復交流。
<%@page import="java.util.*,
java.net.*,
java.text.*,
java.util.zip.*,
java.io.*"
%>
<%
request.setCharacterEncoding("GBK");
String filePath = request.getParameter("downfile");
String fileName = request.getParameter("filename");
System.out.println(filePath);
File f = new File(filePath);
System.out.println("filename:"+f.getName());
if (f.exists() && f.canRead()) {
response.setContentType("application/x-msdownload");
//response.setHeader("Content-Disposition", "attachment;filename=/"" + java.net.URLEncoder.encode(f.getName(),"UTF-8") + "/"");
response.setHeader("Content-Disposition", "attachment;filename=/"" + new String(f.getName().getBytes("GBK"),"iso8859-1") + "/"");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(f));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
}
} catch(final IOException e) {
System.out.println ( "IOException." + e );
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
bos.flush();
bos.close();
bos=null;
response.flushBuffer();
out.clear();
out = pageContext.pushBody();
return;
}
else
{
out.println("File Not Found!!!");
}
%>