JAVA WEB 如何实现随机验证码

4.1 实现验证码
4.1.1 需求
1.当用户访问网页时,出现随机的验证码图片。
2.用户可以更换验证码图片。
3.验证码的数字或者字母不对齐。
4.验证码图片随机从左侧到右侧的直线
5.验证码颜色随机。

4.1.2 实现原理
1.通过servlet的servletOutputStream给用户传图片输出流。
2.通过ImageIo工具类,将图片类转换为输出流。
3.通过BufferedImage类创建图片类。
4.通过Graphics2D类(图片类.createGraphics()方法获取),获取图片类的画板。
5.使用Graphics2D(画板),进行绘画。

4.1.3 步骤
4.1.3.1 创建一个图片,并获得图片画板
//创建一张图片
BufferedImage image = new BufferedImage(50,100,BufferedImage.TYPE_INT_RGB);
//获取图片的画板
Graphics2D graphics = image.createGraphics();

4.1.3.2 生成随机数
/存放验证码
List list = new ArrayList<>();
//产生随机数
Random random = new Random();
//随机范围
for (int i = 0; i < 4; i++) {
//数字还是字母
String NumOrChar = random.nextInt(2)%20?“CHAR”:“NUM”;
if (NumOrChar.equals(“CHAR”)) {
//大小还是小写
int start = random.nextInt(2)%2
0?65:97;
list.add((char)(random.nextInt(26)+start)+"");//26个字母
}else {
list.add(random.nextInt(10)+"");
}
}
//1.用一个list存放生成的4个验证码,因为需要将验证码在不同坐标画出,所以要分开。
//2.random.nextInt(2)%2只有0和1的情况,所以根据随机决定验证码是数字还是字母。
//3.random.nextInt(2)%2==0?65:97; ASCII码中小写从65开始,大写从97开始,所以先随机个起始值。
//4.(char)(random.nextInt(26)+start)+"":一个26个字母,所以随机从0-25,再加上初始ASCII码。

4.1.3.3 画图片背景
//画图
//先给背景,白色
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, 200, 100);

4.1.3.4 画验证码字符串
//再画字符串
Color[] colors = new Color[]{Color.RED,Color.BLUE,Color.GREEN,Color.PINK,Color.GRAY};
graphics.setFont(new Font(“宋体”, Font.ITALIC|Font.BOLD,40));
for (int i = 0, j = 0; i <list.size(); i++) {
graphics.setColor(colors[random.nextInt(5)]);//随机颜色
graphics.drawString(list.get(i),j,random.nextInt(60)+40);
j+=40;
}
//1.创建颜色数组,用于随机验证码的颜色
//2.random.nextInt(60)+40 :y轴40位字体高度,60为范围。
//3.j+=40;每个验证码40宽度,

4.1.3.5 画干扰线和边框
//画线,3条线
for (int i = 0; i ❤️ ; i++) {
graphics.setColor(colors[random.nextInt(5)]);//随机颜色
graphics.drawLine(0,random.nextInt(100),200,random.nextInt(100));
}
//画边框
graphics.setColor(Color.black);
graphics.drawRect(0, 0, 199, 99);
//干扰线x轴从矩形的最左边0到矩形的最右边200,y轴的值是随机的。
//graphics.drawRect(0, 0, 199, 99); 边框的线宽度为1,所以高宽都-1.

4.1.3.6 通过servlet返回给用户
//输出流
ServletOutputStream outputStream = response.getOutputStream();
//工具类
ImageIO.write(image,“jpg”,outputStream);
HttpSession session = request.getSession();
session.setAttribute(“validCode”,list.get(0)+list.get(1)+list.get(2)+list.get(3));
//response.getOutputStream();获取servlet的的输出流对象。
//ImageIO.write(image,“jpg”,outputStream);通过工具类将图片写入输出流对象。
//然后将验证码字符串保存到session中,提供给验证的servlet进行验证。


加上页面代码

<%--
  Created by IntelliJ IDEA.
  User: thinkpad T440S
  Date: 2019/2/21
  Time: 12:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="js/jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(function () {
            $("a").click(function () {
                    $("#validCode").attr("src","validCode?date="+new Date());
                    return false;//阻止提交表达
                })
        });
    </script>
</head>
<body>

<span style="color: #f34222;">${error }</span>
<form action="login" method="post" >
    用户名:<input type="text" id="username"  name="username" value="请输入用户名"><br>
    密码:<input type="password" id="password" name="password" ><br>
    验证码:<input type="text"  name="validCode"><br>
    <img src="validCode" id="validCode" alt="" width="100" height="50">
    <a href="">看不清</a><br>
    <input type="submit" id="commit">
</form>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_43354959/article/details/87872552
今日推荐