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()相沖突的!所以會出現以上這個異常。然后當然是要提出解決的辦法,其實挺簡單的(并不是和某些朋友說的那樣--將jsp內的所有空格和回車符號所有都刪除掉),在使用完輸出流以后調用以下兩行代碼即可:
out.clear();
out = pageContext.pushBody();
附:產生驗證碼圖片的文件image.jsp
1
<%@ page contentType="image/jpeg"
2
import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"
3
pageEncoding="GBK"%>
4
<%!Color getRandColor(int fc, int bc)
{//給定范圍獲得隨機顏色
5
Random random = new Random();
6
if (fc > 255)
7
fc = 255;
8
if (bc > 255)
9
bc = 255;
10
int r = fc + random.nextInt(bc - fc);
11
int g = fc + random.nextInt(bc - fc);
12
int b = fc + random.nextInt(bc - fc);
13
return new Color(r, g, b);
14
}%>
15
<%
16
//設置頁面不緩存
17
response.setHeader("Pragma", "No-cache");
18
response.setHeader("Cache-Control", "no-cache");
19
response.setDateHeader("Expires", 0);
20
// 在內存中創建圖象
21
int width = 60, height = 20;
22
BufferedImage image = new BufferedImage(width, height,
23
BufferedImage.TYPE_INT_RGB);
24
// 獲取圖形上下文
25
Graphics g = image.getGraphics();
26
//生成隨機類
27
Random random = new Random();
28
// 設定背景色
29
g.setColor(getRandColor(200, 250));
30
g.fillRect(0, 0, width, height);
31
//設定字體
32
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
33
//畫邊框
34
//g.setColor(new Color());
35
//g.drawRect(0,0,width-1,height-1);
36
// 隨機產生155條干擾線,使圖象中的認證碼不易被其它程序探測到
37
g.setColor(getRandColor(160, 200));
38
for (int i = 0; i < 155; i++)
{
39
int x = random.nextInt(width);
40
int y = random.nextInt(height);
41
int xl = random.nextInt(12);
42
int yl = random.nextInt(12);
43
g.drawLine(x, y, x + xl, y + yl);
44
}
45
// 取隨機產生的認證碼(4位數字)
46
String sRand = "";
47
for (int i = 0; i < 4; i++)
{
48
String rand = String.valueOf(random.nextInt(10));
49
sRand += rand;
50
// 將認證碼顯示到圖象中
51
g.setColor(new Color(20 + random.nextInt(110), 20 + random
52
.nextInt(110), 20 + random.nextInt(110)));
53
//調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接生成
54
g.drawString(rand, 13 * i + 6, 16);
55
}
56
// 將認證碼存入SESSION
57
session.setAttribute("rand", sRand);
58
// 圖象生效
59
g.dispose();
60
// 輸出圖象到頁面
61
ImageIO.write(image, "JPEG", response.getOutputStream());
62
out.clear();
63
out = pageContext.pushBody();
64
%>
在html中使用驗證碼圖片:
1
<img src="image.jsp" id="src" height="18" alt="看不清楚?請點擊刷新" onclick="this.src=this.src+'?'+Math.random();" />
posted on 2009-03-11 21:07
飛翔天使 閱讀(305)
評論(0) 編輯 收藏 所屬分類:
JSP