zoukankan      html  css  js  c++  java
  • java生成验证码并进行验证

    一实现思路

    1. 使用BufferedImage用于在内存中存储生成的验证码图片
    2. 使用Graphics来进行验证码图片的绘制,并将绘制在图片上的验证码存放到session中用于后续验证
    3. 最后通过ImageIO将生成的图片进行输出
    4. 通过页面提交的验证码和存放在session中的验证码对比来进行校验

    二、生成验证码

    页面通过访问servlet来生成验证码,servlet中的代码如下

    package org.test;
    
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.Random;
    
    import javax.imageio.ImageIO;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author worm0527
     * 2016-03-22 23:15:54
     * 生成验证码
     */
    public class ImageServlet extends HttpServlet{
        // 图片高度
        private static final int IMG_HEIGHT = 100;
        // 图片宽度
        private static final int IMG_WIDTH = 30;
        // 验证码长度
        private static final int CODE_LEN = 4;
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            // 用于绘制图片,设置图片的长宽和图片类型(RGB)
            BufferedImage bi = new BufferedImage(IMG_HEIGHT, IMG_WIDTH, BufferedImage.TYPE_INT_RGB);
            // 获取绘图工具
            Graphics graphics = bi.getGraphics();
            graphics.setColor(new Color(100, 230, 200)); // 使用RGB设置背景颜色
            graphics.fillRect(0, 0, 100, 30); // 填充矩形区域
    
            // 验证码中所使用到的字符
            char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456".toCharArray();
            String captcha = ""; // 存放生成的验证码
            Random random = new Random();
            for(int i = 0; i < CODE_LEN; i++) { // 循环将每个验证码字符绘制到图片上
                int index = random.nextInt(codeChar.length);
                // 随机生成验证码颜色
                graphics.setColor(new Color(random.nextInt(150), random.nextInt(200), random.nextInt(255)));
                // 将一个字符绘制到图片上,并制定位置(设置x,y坐标)
                graphics.drawString(codeChar[index] + "", (i * 20) + 15, 20);
                captcha += codeChar[index];
            }
            // 将生成的验证码code放入sessoin中
            req.getSession().setAttribute("code", captcha);
            // 通过ImageIO将图片输出
            ImageIO.write(bi, "JPG", resp.getOutputStream());
        }
    
    }



    
    

    三、校验验证码

    通过前台提交的验证码与session中数据进行对比来校验验证码,代码如下:

    package org.test;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class CheckCodeServlet extends HttpServlet{
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            // 获取存放在session中的验证码
            String code = (String) req.getSession().getAttribute("code");
            // 获取页面提交的验证码
            String inputCode = req.getParameter("code");
            if(code.toLowerCase().equals(inputCode.toLowerCase())) { // 验证码不区分大小写
                // 验证成功,跳转到成功页面
                req.getRequestDispatcher("/success.jsp").forward(req, resp);
            } else { // 验证失败
                req.getRequestDispatcher("/fail.jsp").forward(req, resp);
            }
        }
    
    }

    验证码提交页面html代码:

    <form action="<%=request.getContextPath() %>/checkCode" method="post">
        请输入验证码:<input type="text" name="code">
        <input type="submit" value="确定">
    </form>
    <img alt="验证码" id="scode" src="<%=request.getContextPath() %>/getCode" >
    <a href="#" onclick="javascript:flushCode();">看不清?</a>

    当生成的验证码不清楚时需要刷新重新生成验证码,js代码如下:

    function flushCode() {
        // 每次刷新的时候获取当前时间,防止浏览器缓存刷新失败
        var time = new Date();
        document.getElementById("scode").src = "<%=request.getContextPath()%>/getCode?time=" + time;
    }



    四、效果展示

    • 生成的验证码

    这里写图片描述

    • 验证成功

    这里写图片描述

    这里写图片描述

    • 验证失败

    这里写图片描述

    这里写图片描述

    五、总结

    本文介绍了验证码的生成和验证,生成的验证码比较简单没有添加线条等干扰因素,比较容易识别。在实际的项目中可采用其他的第三方验证码库来生成验证码。

    以上。

    原文来至:Java生成验证码并进行验证

    作者:

    worm0527的博客


  • 相关阅读:
    LeetCode 40. 组合总和 II(Combination Sum II)
    LeetCode 129. 求根到叶子节点数字之和(Sum Root to Leaf Numbers)
    LeetCode 60. 第k个排列(Permutation Sequence)
    LeetCode 47. 全排列 II(Permutations II)
    LeetCode 46. 全排列(Permutations)
    LeetCode 93. 复原IP地址(Restore IP Addresses)
    LeetCode 98. 验证二叉搜索树(Validate Binary Search Tree)
    LeetCode 59. 螺旋矩阵 II(Spiral Matrix II)
    一重指针和二重指针
    指针的意义
  • 原文地址:https://www.cnblogs.com/a1111/p/6540267.html
Copyright © 2011-2022 走看看