随机验证码出错:
<%@ page contentType= "image/jpeg "%>
<%@ page
import= "java.awt.*,java.awt.image.*,java.util.*,javax.imageio.* "%>
<%!Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}%>
<%
response.setHeader( "Pragma ", "No-cache ");
response.setHeader( "Cache-Control ", "no-cache ");
response.setDateHeader( "Expires ", 0);
int width = 50, height = 18;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font( "Times New Roman ", Font.PLAIN, 16));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 50; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(width);
int yl = random.nextInt(height);
g.drawLine(x, y, x + xl, y + yl);
}
String sRand = " ";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20
+ random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 11 * i + 6, 16);
}
session.setAttribute( "rand ", sRand);
g.dispose();
try {
ImageIO.write(image, "JPEG ", response.getOutputStream());
//就是这里的getOutputStream抛出异常,内
// 容:java.lang.IllegalStateException:
// getOutputStream() has already been called for this response
//程序能运行,不受异常影响,不过还是想知道为什么
} catch (Exception e) {
System.out.println( "catch ");
}
%>
------解决方法--------------------------------------------------------
write( "... ")和response.getOutputStream()产生冲突.
Servlet规范说明,不能既调用 response.getOutputStream(),又调用response.getWriter(),无论先调用哪一个,在调用第二个时候应会抛出 IllegalStateException.
------解决方法--------------------------------------------------------
因为Application Server在处理编译jsp时对于%> 和 <%之间的内容通过PrintWriter输出(包括HTML标签,空格,回车等通过浏览器生成的标识符),而在上面的例子又要进行流输出:ServletOutputStream,这样做相当于试图在Servlet中使用两种输出机制,
就会发生:getOutputStream() has already been called for this response的错误
你把空格这些删除了就好了,jsp页面只写成这样
<%@ page language= "java " import= "java.awt.*,java.awt.image.*,javax.imageio.*,java.util.* " pageEncoding= "GBK "%> <%@ page contentType= "image/jpeg "%> <%!Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);