博主
258
258
258
258

第二节 生成随机数以及验证码工具类

亮子 2022-06-22 06:57:27 45 0 0 0

1、工具类源码

package com.shenmazong.cms.utils;

import java.util.Random;

/**
 * @author 军哥
 * @version 1.0
 * @description: 随机字符串工具类
 * @date 2022/1/23 21:09
 */

public class RandomUtils {

    public static RandomUtils random() {
        return new RandomUtils();
    }

    /**
     * @description 获取定长随机数字字符串
     * @author 军哥
     * @date 2022/1/12 10:56
     * @version 1.0
     */
    public String randomIntCode(int length) {
        String code = "";
        Random random = new Random();
        while (true) {
            if(code.length()>=length) {
                break;
            }
            int i = random.nextInt(9);
            // 排除0开头的数字
            if(i == 0 && code.length() == 0) {
                continue;
            }
            code = code + i;
        }

        return code;
    }

    /**
     * @description 产生字母验证码
     * @author 军哥
     * @date 2022/1/12 12:27
     * @version 1.0
     */
    public String randomLetterCode(int length) {
        String letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();

        String code = "";

        while (true) {
            if(code.length()>=length) {
                break;
            }
            int index = random.nextInt(letters.length()-1);

            code = code + letters.charAt(index);
        }

        return code;
    }

    /**
     * @description 根据字符库生成随机字符串验证码
     * @author 军哥
     * @date 2022/1/12 12:32
     * @version 1.0
     */
    public String randomCode(String letters, int length) {
        Random random = new Random();

        String code = "";

        while (true) {
            if(code.length()>=length) {
                break;
            }
            int index = random.nextInt(letters.length()-1);

            code = code + letters.charAt(index);
        }

        return code;
    }
}