快速入门Servlet之Response验证码(十四)

验证码

本质:图片
目的:防止恶意表单注册

int width = 100;
        int height = 50;
        //1.创建验证码对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        //2.美化图片
        //2.1填充背景色
        Graphics g = image.getGraphics();//画笔对象
        g.setColor(Color.PINK); //设置画笔颜色
        g.fillRect(0, 0, width, height);
        //2.2画边框
        g.setColor(Color.BLUE);
        g.drawRect(0, 0, width - 1, height - 1);
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        //生成随机角标
        Random ran = new Random();
        String yanzhengma = "";
        for (int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
            //获取字符
            char ch = str.charAt(index);//随机字符
            //2.3写验证码
            g.drawString(ch + "", width / 5 * i, height / 2);
            yanzhengma = yanzhengma + ch;
        }
        System.out.println(yanzhengma); //验证码的值
        //2.4画干扰线
        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, x2, y1, y2);
        }
        //设置响应头通知浏览器以图片的形式打开
        resp.setContentType("image/jpeg");
        //设置响应头控制浏览器不要缓存
        resp.setDateHeader("expries", -1);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "no-cache");
        //3.将图片输出到页面展示
        ImageIO.write(image, "jpg", resp.getOutputStream());

点击切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script>
        /**
         * 分析:
         *      点击超链接或者图片,换一张图片
         *      1.给超链接和图片绑定单击事件
         *      2.重新设置图片的src属性值
         */
        window.onload = function () {
            //1.获取图片对象
            var img = document.getElementById("checkCode");
            //2.绑定单击事件
            img.onclick = function () {
                //加时间戳
                var date = new Date().getTime();
                img.src = "/responseDemo01?" + date;
            }
        }

    </script>


</head>
<body>
<img id="checkCode" src="/responseDemo01">
<a id="change" href="">看不清?点击换一张</a>


</body>
</html>

加上验证功能

  • demo1
req.getSession().setAttribute("checkcode", yanzhengma); // 将验证码传到Demo02 用于验证
  • demo2
String serverCheckcode = (String) req.getSession().getAttribute("checkcode");
        String result = req.getParameter("yanzhengma");
        if (serverCheckcode.equals(result)) {
            System.out.println("yes");
        } else {
            System.out.println("no");
        }
  • html
<form action="/responseDemo02" method="post">
    验证码:<input type="text" name="yanzhengma"> <br>
    <input type="submit" value="提交">
</form>
发布了109 篇原创文章 · 获赞 2 · 访问量 1234

猜你喜欢

转载自blog.csdn.net/qq_42528769/article/details/104426022