0%

Servlet验证码

手写验证码

  • 输出随机图片(CAPTCHA 图像):Complrtrly Automated Public Turing Test to Tell Computers and Humans Apart(全自动区分计算机和人类的测试)(这个名字绝对是为了缩写拼凑出来的)。
  • 相关主要类
  • BufferedImage:内存图像
  • Graphics:画笔
  • ImageIO:输出图像
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
@WebServlet("/VerificationCode")
public class VerificationCode extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// BufferedImage:内存图像
// Graphics:画笔
// ImageIO:输出图像

// 创建一个图片对象(画布)
int width =120;
int height =30;
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

// 拿到画笔
Graphics graphics = bi.getGraphics();

// 涂背景颜色
graphics.setColor(Color.white);
graphics.fillRect(0, 0, width, height);

// 画干扰线
// 重新设置画笔颜色
graphics.setColor(Color.red);
Random ran = new Random();
Color[] colors = {Color.blue, Color.green, Color.red};
for(int i=0; i<5; i++) {
graphics.setColor(colors[ran.nextInt(3)]);
int x1 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int x2 = ran.nextInt(width);
int y2 = ran.nextInt(height);
graphics.drawLine(x1, y1, x2, y2);
}

// 画验证码
graphics.setColor(Color.black);
int left = 25;
for(int i=0; i<4; i++) {
int r = ran.nextInt(10);
graphics.drawString(r+"", left, 20);
left+=20;
}

// 设置响应类型
resp.setContentType("image/jpeg");
// 把图片输出给客户端
ImageIO.write(bi, "JPEG", resp.getOutputStream());
}
}
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
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>

<script type="text/javascript">
function refreshCode(){
// 获取img标签
var imgTag = document.getElementById("code");
imgTag.src = '/191023/VerificationCode?' + new Date().getTime();
}
</script>

</head>
<body>
<form action="">
用户名:<input type="text"><br>
密码:<input type="password"><br>
验证码:<input id="code" type="text"><img src="/191023/VerificationCode?">
<!-- 怎么在a标签中,调用js -->
<a href="javascript:refreshCode()">看不清,换一个</a>
<br>
</form>
</body>
</html>