最近用了jsp做了一个简单的图形验证码,产生四个随机字符。使用时候发现后台异常不断。
异常日志如下:
2009-9-10 13:39:23 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:596)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:186)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:124)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:117)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:191)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:115)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
意思就是在输出前已经有out流了,查了整个代码,也没输出啊。灵异事件?
狗了一下,解决了这个问题,修改jsp源码中<%%>和<%%>之间的空格和换行。
原来代码:
<%@page contentType="image/jpeg"%>
<%
// code 11
%>
<%
// code 22
%>
修改后:
<%@page contentType="image/jpeg"%><%
// code 11
%><%
// code 22
%>
原因应该是page声明那一行会默认一个输出空行,而Content-type是image就会出错啦!
下面是验证码的源码,有需要的就扒一下把:
<%@page contentType="image/jpeg" 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 = 60, height = 20;
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("Verdana Arial Helvetica sans-serif", Font.PLAIN, 20));
g.setColor(getRandColor(160, 255));
for (int i = 0; i < 200; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(10);
int yl = random.nextInt(10);
g.drawLine(x, y, x + xl, y + yl);
}
char c[] = new char[62];
for (int i = 97, j = 0; i < 123; i++, j++) {
c[j] = (char) i;
}
for (int o = 65, p = 26; o < 91; o++, p++) {
c[p] = (char) o;
}
for (int m = 48, n = 52; m < 58; m++, n++) {
c[n] = (char) m;
}
String sRand = "";
for (int i = 0; i < 4; i++) {
int x = random.nextInt(62);
String rand = String.valueOf(c[x]);
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
g.dispose();
ImageIO.setUseCache(true);
ImageIO.write(image, "JPEG", response.getOutputStream());
session.setAttribute("rand", sRand);
%>