生成有个随机数字和杂乱背景的图片数字和背景颜色会改变服务器端刷新(用historygo()也会变)
原型参考ALIBABA
产生验证码图片的文件imagejsp
<%@ page contentType=image/jpeg import=javaawt*javaawtimage*javautil*javaximageio* %>
<%!
Color getRandColor(int fcint bc){//给定范围获得随机颜色
Random random = new Random();
if(fc>) fc=;
if(bc>) bc=;
int r=fc+randomnextInt(bcfc);
int g=fc+randomnextInt(bcfc);
int b=fc+randomnextInt(bcfc);
return new Color(rgb);
}
%>
<%
//设置页面不缓存
responsesetHeader(PragmaNocache);
responsesetHeader(CacheControlnocache);
responsesetDateHeader(Expires );
// 在内存中创建图象
int width= height=;
BufferedImage image = new BufferedImage(width height BufferedImageTYPE_INT_RGB);
// 获取图形上下文
Graphics g = imagegetGraphics();
//生成随机类
Random random = new Random();
// 设定背景色
gsetColor(getRandColor());
gfillRect( width height);
//设定字体
gsetFont(new Font(Times New RomanFontPLAIN));
//画边框
//gsetColor(new Color());
//gdrawRect(widthheight);
// 随机产生条干扰线使图象中的认证码不易被其它程序探测到
gsetColor(getRandColor());
for (int i=;i<;i++)
{
int x = randomnextInt(width);
int y = randomnextInt(height);
int xl = randomnextInt();
int yl = randomnextInt();
gdrawLine(xyx+xly+yl);
}
// 取随机产生的认证码(位数字)
String sRand=;
for (int i=;i<;i++){
String rand=StringvalueOf(randomnextInt());
sRand+=rand;
// 将认证码显示到图象中
gsetColor(new Color(+randomnextInt()+randomnextInt()+randomnextInt()));//调用函数出来的颜色相同可能是因为种子太接近所以只能直接生成
gdrawString(rand*i+);
}
// 将认证码存入SESSION
sessionsetAttribute(randsRand);
// 图象生效
gdispose();
// 输出图象到页面
ImageIOwrite(image JPEG responsegetOutputStream());
%>
使用验证码图片的文件ajsp
<%@ page contentType=text/html;charset=gb %>
<!DOCTYPE HTML PUBLIC //WC//DTD HTML Transitional//EN>
<html>
<head>
<title>认证码输入页面</title>
<meta httpequiv=ContentType content=text/html; charset=gb>
<META HTTPEQUIV=Pragma CONTENT=nocache>
<META HTTPEQUIV=CacheControl CONTENT=nocache>
<META HTTPEQUIV=Expires CONTENT=>
</head>
<body>
<form method=post action=checkjsp>
<table>
<tr>
<td align=left>系统产生的认证码</td>
<td><img border= src=imagejsp></td>
</tr>
<tr>
<td align=left>输入上面的认证码</td>
<td><input type=text name=rand maxlength= value=></td>
</tr>
<tr>
<td colspan= align=center><input type=submit value=提交检测></td>
</tr>
</form>
</body>
</html>
验证的页面checkjsp
<%@ page contentType=text/html; charset=gb language=java import=javasql* errorPage= %>
<html>
<head>
<title>认证码验证页面</title>
<meta httpequiv=ContentType content=text/html; charset=gb>
<META HTTPEQUIV=Pragma CONTENT=nocache>
<META HTTPEQUIV=CacheControl CONTENT=nocache>
<META HTTPEQUIV=Expires CONTENT=>
</head>
<body>
<%
String rand = (String)sessiongetAttribute(rand);
String input = requestgetParameter(rand);
%>
系统产生的认证码为 <%= rand %><br>
您输入的认证码为 <%= input %><br>
<br>
<%
if (randequals(input)) {
%>
<font color=green>输入相同认证成功!</font>
<%
} else {
%>
<font color=red>输入不同认证失败!</font>
<%
}
%>
</body>
</html>