需求分析

  1. 本质上是图片,用来防止恶意表单注册。

    通过img标签,src为servlet的 路径

步骤

  • 书写静态页面login.html

    img标签,src为servlet路径。再写一个a标签。两者都绑定点击事件,点击后图片进行刷新。

  • 书写servlet

    通过ImageIO将写好的img输出到页面流里面去(response.getOutPutStream)

    1
    2
    //将图片写入到浏览器页面上去
    ImageIO.write(img,"jpg",response.getOutputStream());

代码

登录页面login.html

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
<script>
window.onload=function () {
var img=document.getElementById("image");
var change=document.getElementById("change");
img.onclick=function() {
var date=new Date().getTime();
img.src="/day/CheckCodeServlet?"+date;
}
change.onclick=function() {
var date=new Date().getTime();
img.src="/day/CheckCodeServlet?"+date;
}
}
</script>
</head>
<body>

<img src="/day/CheckCodeServlet" id="image">
<a href="" id="change">看不见?点击换一张</a>
</body>
</html>

CheckCodeServlet

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
50
51
52
53
54
55
56
package cn.itcast.web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int height=50;
int width=100;
//创建对象,在内存中图片对象
BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);


//美化图片
Graphics g = img.getGraphics();
g.setColor(Color.pink);
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 c = str.charAt(index);
g.drawString(c+"",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,x1,x2);

}


//将图片写入到浏览器页面上去
ImageIO.write(img,"jpg",response.getOutputStream());


}
}

演示

在这里插入图片描述

项目总结

验证码实现的原理?

验证码的本质是一张图片,通过设置图片标签的src指向servlet位置,通过在servlet中定义img的内容,然后通过ImageIO.write 将img内容写到response的输出流上去,也就是输出到页面中。