验证码的简单实现

1、创建CheckCodeServlet类,生成验证码

@WebServlet("/checkcode")
public class Demo6_CheckCode extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int width = 100;
        int height = 50;

        // 1.创建一个对象,在内存中(验证码图片对象)
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);

        // 2. 美化图片
        // 2.1 填充背景色
        Graphics graphics = img.getGraphics();  // 获取画笔对象
        graphics.setColor(Color.pink);          // 设置画笔颜色
        graphics.fillRect(0, 0, width, height); // 填充
        // 2.2 画边框
        graphics.setColor(Color.blue);
        graphics.drawRect(0, 0, width - 1, height - 1);// 线本身就有1px,所以x方向和y方向画的长度都要-1


        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        // 生成随机角标
        Random random = new Random();
        for (int i = 1; i <= 4; i++) {
            int index = random.nextInt(str.length());// 获取随机角标
            char c = str.charAt(index); // 获取字符
            // 2.3 写验证码
            graphics.drawString(c+"", width/5 * i, height/2);
        }

        // 2.4 绘制干扰线
        graphics.setColor(Color.green);
        // 随机生成坐标点
        for (int i = 0; i < 10; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(width);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(width);
            graphics.drawLine(x1, y1, x2, y2);
        }


        // 3. 将图片输出到页面展示
        boolean input = ImageIO.write(img, "jpg", response.getOutputStream());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

2、创建register.html,使用生成的二维码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册页面</title>

    <script>
        /*
        分析:点击超链接,换一张验证码图片
            1. 给超链接和图片绑定单击事件
            2. 重新设置图片的src属性
        **/

        window.onload = function() {
            // 1. 获取图片对象
            var img = document.getElementById("checkcode");
            img.onclick = function () {
                // 设置img的src属性
                // img.src = "/response/checkcode"; // 这种设置方式,点击图片时无法正常展示出刷新的图片。因为之前加载的img已经被浏览器缓存了,每次展示的都是缓存中的图片。

                // 加时间戳参数
                var date = new Date().getTime();
                img.src = "/response/checkcode?" + date;
            }


            var link = document.getElementById("change");
            link.onclick = function () {
                var date = new Date().getTime();
                img.src = "/response/checkcode?" + date;
            }
        }


    </script>

</head>
<body>
    <img id="checkcode" src="/response/checkcode">
    <a id="change" href="#">看不清换一张?</a>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_41463971/article/details/88653961