avatar

简单的验证码实现逻辑及点击切换

为了防止恶意表单注册,注册界面都会加上验证码功能。服务器会在内存生成验证码图片,并显示随机内容到网页,并且要防止智能识别。具体代码如下:

验证码图片生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 50;
//创建一个对象,在内存中画图(验证码图片对象)
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
//美化图片
//填充背景色
Graphics g = image.getGraphics();//画笔对象
g.setColor(Color.pink);//设置画笔颜色
g.fillRect(0,0,width,height);
//画边框
g.setColor(Color.BLUE);
g.drawRect(0,0,width -1,height-1);

String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//生成随机脚标
Random ran = new Random();

//写验证码
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(str.length());
//获取字符
char ch = str.charAt(index);
g.drawString(ch+"",width/5*i,height/2);
}

//画干扰线
g.setColor(Color.green);
//随机生成坐标点
for (int i = 0; i < 10; i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);

int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}

//键土拍你输出到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}

图片点击切换

1
2
3
4
<body>
<img id="checkCode" src="/day15/checkCodeServlet" onclick="this.src='/day15/checkCodeServlet?' + new Date().getTime();"/>
<a id="change" href="">看不清换一张</a>
</body>

服务器会有图片缓存,路径不变的画服务器不会发送新数据到客户端,验证码就不能刷新,可以加随机数或时间戳到路径后。


评论