图例如下
具体操作如下:
新建一个servlet,代码如下:标记一个WebServlet,
1 @WebServlet(urlPatterns = {"/checkCode"}) //验证码Servlet
绘制验证码图片的核心代码:
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
|
int width = 100 ;
int height = 50 ;
//创建图片对象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//美化图片
Graphics g = image.getGraphics();
// 1 :填充背景
g.setColor(Color.pink);
g.fillRect( 0 , 0 , width, height);
//画边框
g.setColor(Color. blue );
g.drawRect( 0 , 0 , width - 1 , height - 1 );
//生成一个验证码字符串
String strCheckCode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ;
Random random = new Random();
StrCheckCode = "" ;
for (int i = 1 ; i <= 4 ; i++) {
int index = random.nextInt(strCheckCode.length());
char ch = strCheckCode.charAt(index);
StrCheckCode += ch;//拼接验证码
g.drawString(ch + "" , width / 5 * i, height / 2 );
}
//画干扰线
for (int i = 0 ; i < 5 ; i++) {
int x 1 = random.nextInt(width);
int x 2 = random.nextInt(width);
int y 1 = random.nextInt(height);
int y 2 = random.nextInt(height);
g.drawLine(x 1 , x 2 , y 1 , y 2 );
}
//输出,显示出来
ImageIO.write(image, "jpg" , resp.getOutputStream());
}
|
首先是new一个BufferedImage,然后给定长和宽,之后是指边框和背景色,接着使用随机数生成4个字符绘制在图片上,接着使用DrawLine绘随机制干扰线,
然后在前端页面引入图片,然后给图片绑定点击事件,点击后重新访问servlet即可:
1
2
3
4
5
6
7
8
|
//点击验证码图片,重新生成新验证
$( function () {
$( "#imgCheckCode" ).click( function () {
var img = document.getElementById( "imgCheckCode" );
var date = new Date();
img.src = "http://localhost:8080/blogs_war_exploded/checkCode?op=setCheckCode&a=" + date;
})
})
|
1
2
3
4
5
6
7
|
< div class = "inputCheckCode" >
< div class = "inputCheckCodeLeftIco" >➤</ div >
< div class = "inputCheckCodeRightInput" >
< input type = "text" name = "checkCode" id = "checkCode" placeholder = "验证码" autocomplete = "off" />
</ div >
< img src = "http://localhost:8080/blogs_war_exploded/checkCode?op=setCheckCode" id = "imgCheckCode" >
</ div >
|
最后输出即可,效果如下:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/lwl80/p/13551559.html