web中验证码的实现
页面上的连接地址和验证码的图片
function loadimage(){
document.getElementById("randImage").src = "image.jsp?"+Math.random();
//生成一张图片,产生的地址是`image.jsp` + `一个随机数` 使产生的地址不同,浏览器不缓存。
}
<td><label>验证码:</label></td>
<td>
<input class="text" style="margin-right: 10px;" type=text value="${imageCode }" name="rand">
<img onclick="loadimage();" title="换一张试试" name="randImage" id="randImage" src="image.jsp" border="1" align="absmiddle">
</td>
- image.jsp
产生图片并且显示图片。
<%@ 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);//随机生成RGB颜色中的r值
int g=fc+random.nextInt(bc-fc);//随机生成RGB颜色中的g值
int b=fc+random.nextInt(bc-fc);//随机生成RGB颜色中的b值
return new Color(r,g,b);
}
%>
<%
out.clear();//这句针对resin服务器,如果是tomacat可以不要这句
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("Times New Roman",Font.PLAIN,18));
g.setColor(getRandColor(160,200));
//产生随机条虚线
for (int i=0;i<155;i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
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,13*i+6,16);
}
// 将认证码存入SESSION
session.setAttribute("rand",sRand);
g.dispose();//释放g所占用的系统资源
ImageIO.write(image, "JPEG", response.getOutputStream());//输出图片
%>
- 将处理输入的值与sessiond的值进行对比
String rand = (String)session.getAttribute("rand");
String input = request.getParameter("rand");
<%
if(!rand.equals(input)){
%>
<script>
alert("验证码错误!");
window.location.href="你想要返回的页面";
</script>
<%
}%>