验证码的作用:
1、为了防止机器冒充人类做暴力破解
2、防止大规模在线注册滥用服务
3、防止滥用在线批量操
4、防止自动发布
5、防止信息被大量采集聚合
随机生成一个字母数字组合的验证码
1.创建一个集合添加所有的大写和小写字母
2.随机抽取四个字符
3.把一个10位随机数字添加到 末尾
技术:
ArrayList<> StringBuffer Random
代码解析:
/**
* @Classname Test
* @Author:ZhenYi
*/
public class Test {
public static void main(String[] args) {
getCode();
}
//生成验证码
private static String getCode() {
//1.创建一个集合添加所有的大写和小写字母
ArrayList<Character> list = new ArrayList<>();
for (int i = 0; i < 26; i++) {
list.add((char) ('a' + i));//强转字符
list.add((char) ('A' + i));
}
//System.out.println(list);大小写字符
StringBuffer sb = new StringBuffer();
//2.随机抽取四个字符
Random rand = new Random();
for (int i = 0; i < 4; i++) {
//获取随机索引
int index = rand.nextInt(list.size());
//利用随机索引获取字符
//jdk 5以后char和character
char c = list.get(index);
//把随机字符c添加到sb中
sb.append(c);
}
//System.out.println(sb);//四个随机字符
//3.把一个10位随机数字添加到 末尾
int number=rand.nextInt(10);
sb.append(number);
System.out.println(sb);
return "";
}
}