生成验证码
验证码是一个保障接口和用户密码安全的良好工具,在项目中进行一些比较“危险”的操作的时候我们需要让输入验证码才能进入到下一步,话不多说,先来编写一个验证码工具类:
新建验证码实体类
在bean子包下新建VerifyCode实体类:
/**
* @Author Alfalfa99
* @Date 2020/9/19 22:13
* @Version 1.0
* 验证码实体类
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class VerifyCode {
private String code;
private byte[] imgBytes;
private long expireTime;
}
新建验证码工具类
在util包下新建一个VerifyCodeUtil:
import Echo.alfalfa.MemberManager.model.bean.VerifyCode;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
/**
* @Author Alfalfa99
* @Date 2020/9/19 22:10
* @Version 1.0
* 验证码生成工具类
*/
public class VerifyCodeUtil extends org.apache.commons.lang3.RandomUtils {
private static final char[] CODE_SEQ = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
private static final char[] NUMBER_ARRAY = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
private static Random random = new Random();
public static String randomString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.valueOf(CODE_SEQ[random.nextInt(CODE_SEQ.length)]));
}
return sb.toString();
}
public static String randomNumberString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.valueOf(NUMBER_ARRAY[random.nextInt(NUMBER_ARRAY.length)]));
}
return sb.