目录
1.介绍
使用servlet开发web时,如何在后端生成验证码,提供给前端使用。
2.思路
使用Java自带的BufferImage类绘制。
3.代码
Serlet中的代码:
// 定义验证码图片大小
final int width = 60;
final int height = 30;
// 创建画板,绘制验证码
BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
// 设置验证码图片的背景颜色
graphics.setColor(Color.white);
graphics.fillRect(0,0,width,height);
// 取验证码值,并绘制到图片上
graphics.setColor(new
Color(getRandomInt(0,255),getRandomInt(0,255),getRandomInt(0,255)));
String randomCode =getRandomCode();
graphics.setFont(new Font("黑体",Font.BOLD,18));
graphics.drawString(randomCode,15,20);
response.setContentType("image/jpeg");
graphics.setColor(new Color(getRandomInt(0,255),getRandomInt(0,255),getRandomInt(0,255)));
graphics.drawLine(0,getRandomInt(0,height/2),width,getRandomInt(height/2,height));
// 保存验证码到session
request.getSession().setAttribute("VerifyCode",randomCode);
ImageIO.write(bufferedImage,"jpg",response.getOutputStream());
辅助函数:
/**
* 获取指定范围的随机数
* @param min
* @param max
* @return
*/
private int getRandomInt(int min,int max){
Random random = new Random();
return random.nextInt(max - min + 1) + min;
}
/**
* 获取随机字符串
* @return
*/
private String getRandomCode(){
final String dics="1234567890abcdefghizklmnopqrstuvwxyzABCDEFGHIZKLMNOPQRSTUVWXYZ";
int oneBit = getRandomInt(0,dics.length() - 1);
int towBit = getRandomInt(0,dics.length() - 1);
int threeBit = getRandomInt(0,dics.length() - 1);
int fourBit = getRandomInt(0,dics.length() - 1);
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(dics.charAt(oneBit));
stringBuffer.append(dics.charAt(towBit));
stringBuffer.append(dics.charAt(threeBit));
stringBuffer.append(dics.charAt(fourBit));
return stringBuffer.toString();
}