java实现随机生成验证码工具类

一、什么是验证码

验证码就是将一串随机产生的数字或符号或字母以及混合,生成一幅图片, 图片里加上一些干扰象素(就是经常看到的数字或字母歪歪扭扭的),由用户肉眼识别其中的验证码信息,输入表单提交网站验证,验证成功后才能使用某项功能。现在多使用页面、短信、邮箱等方式进行发送进行操作。

二、代码实现

1.第一种

纯数字:0—9之间数字进行随机

2.第二种

纯字母:26英文字母大小写混搭

3.第三种

纯汉字:随机定义汉字内容进行随机筛选,和第二种一样,可自定义处理。

/**
* @Description:    生成6位随机验证码工具类
* @Author:         Joe
* @CreateDate:     2020/3/15 12:51
*/
public class VerificationCode {

    /**
     * 1.纯数字随机验证码
     * @return
     */
    public static String getNumeral(){
        String code = "";
        for (int i = 0; i < 6; i++) {
            code = code + (int)(Math.random() * 9);
        }
        return code;
    }

    /**
     * 2.纯字母随机验证码
     * @return
     */
    public static String getAlphabet(){
        String code = "";
        char[] ch = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K','L', 'M', 'N', 'O', 'P', 'Q','R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        for (int i = 0; i < 6; i++) {
            int index = (int)(Math.random() * ch.length);
            code = code + ch[index];
        }
        return code;
    }

    /**
     * 3.纯汉字随机验证码
     * @return
     */
    public static String getChinese(){
        String code = "";
        char[] ch = {'你', '看', '见', '过','我', '的', '小', '熊', '了', '吗'};
        for (int i = 0; i < 6; i++) {
            int index = (int)(Math.random() * ch.length);
            code = code + ch[index];
        }
        return code;
    }

    public static void main(String[] args) {
        System.out.println("纯数字验证码:"+getNumeral());
        System.out.println("纯字母验证码:"+getAlphabet());
        System.out.println("纯汉字验证码:"+getChinese());
    }
}

发布了23 篇原创文章 · 获赞 3 · 访问量 1221

猜你喜欢

转载自blog.csdn.net/Joe14103/article/details/104877422
今日推荐