public String getCheckCode(){
String base = "0123456789ABCDEFGabcdefg";
int size = base.length();
Random random = new Random();
StringBuffer stringBuffer = new StringBuffer();
for(int i = 0; i <= 4; i++){
//产生0——size-1的随机值
int index = random.nextInt(size);
//在base字符串中获取下标为index的字符
char c = base.charAt(index);
//将c放入到StringBuffer中去
stringBuffer.append(c);
}
return stringBuffer.toString();
}
调用:
//产生4个随机验证码
String checkCode = getCheckCode();
//将验证码放入HttpSession中
request.getSession().setAttribute("CHECKCODE_SERVER", checkCode);