课程名称:三小时轻松掌握常用验证码制作
课程章节:第1章-验证码的介绍和作用
课程讲师:十方上下
课程内容:
1. 验证码的分类和表现方式
-
随机字符串验证码
随机字符串验证码,就是随机生成由大写字母或小写字母或数字或汉字组成的字符串。
优点:生成方便,识别难度可调节。
缺点:识别难度不好掌握,识别度高容易被程序识别,识别度低用户体验较差。
原理:创建一个画板,将生成的随机字符串随机的画到画板中,再将画板存为图片。
-
算术验证码
-
滑块验证码
-
点击验证码
2. 验证码的作用
- 主要是为了区分用户是真人还是非法程序。
3. 验证码的实现
3.1 随机字符串验证码的实现-Java实现
package com.zhoufengbin.servlet;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class RandonStringCodeServlet extends HttpServlet {
private Random random = new Random();
private int width = 80;
private int height = 30;
private int fontSize = 12;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.创建画板 宽度 高度 字体颜色
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//2.创建画笔
Graphics2D pen = bufferedImage.createGraphics();
//3.生成随机内容
String code = "1234";
//4.绘制内容
//4.1设置绘制区域
pen.fillRect(0, 0, width, height);
//4.2设置字体
pen.setFont(new Font("微软雅黑", Font.BOLD, fontSize));
//4.3按顺序绘制字符
for (int i = 0; i < code.length(); i++){
pen.setColor(randomColor());
pen.drawString(code.charAt(i)+"", 5+i*fontSize, (fontSize+height)/2);
}
//4.4绘制噪音线
//5.存为图片发送
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bufferedImage, "png", out);
out.flush();
out.close();
}
private Color randomColor(){
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r, g, b);
}
}
<%--
Created by IntelliJ IDEA.
User: zfb22
Date: 2022/9/5
Time: 20:44
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>随机字符串验证码</title>
<style>
.code_a {
color: #0000ff;
font-size:12px;
text-decoration: none;
cursor: pointer;
}
#imgCode {
cursor: pointer;
}
</style>
</head>
<body>
<form action="" method="post">
<label>验证码</label>
<input type="text" id="inCode" name="inCode"/>
<img src="first" align="center" id="imgCode"/>
<a class="code_a">换一张</a><br>
<input type="submit" value="登录"/>
</form>
<div >${err}</div>
</body>
</html>
- 效果图