今天我们直接上代码来介绍一下关于网络编程中网页中的验证码生成的方法
<%
//nocache指示请求或响应消息不能缓存
responsesetHeader(CacheControl nocache);
int width = height = ;
//在内存中创建图像
BufferedImage image = new BufferedImage(width height
BufferedImageTYPE_INT_RGB);
//获取画笔
Graphics g = imagegetGraphics();
//设置画笔颜色
gsetColor(ColorWHITE);
gfillRect( width height);
//开始生成验证码这里用加法求和
Random r = new Random();
int num = rnextInt();//操作数
int num = rnextInt();//操作数
int result = num + num;//加法和结果
String code = StringvalueOf(result);
//将验证码存入session
sessionsetAttribute(code code);
//将验证码显示到图像中
gsetColor(ColorBLACK);
gsetFont(new Font( FontPLAIN ));
gdrawString(num+++num+= ? );
//随即产生干扰图像
//随即产生条直线
for (int i = ; i < ; i++) {
int x = rnextInt(width);
int y = rnextInt(height);
gsetColor(ColorRED);
gdrawLine(width/(x+) height/(y+) x y);
}
//产生个点
for(int i=;i<;i++) {
int x = rnextInt(width);
int y = rnextInt(height);
gsetColor(ColorBLUE);
gdrawOval(x y );
}
ImageIOwrite(image JPEG responsegetOutputStream());
outclear();
out = pageContextpushBody();
%>
td><img id=validation src=validationjsp onclick=refresh()>引用验证码即可