protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Random random = new Random();
int colorRandoMin = 200;
int colorRandoMax = 255;
// int randomNum = random.nextInt(randoMax) % (randoMax - randoMin + 1)
// + randoMin;
// 生成验证码
BufferedImage bufferedImage = new BufferedImage(68, 23,
BufferedImage.TYPE_INT_RGB);
// 绘图上上下文对象
Graphics graphics = bufferedImage.createGraphics();
// 画个背景
// 三元色数值随机产生
// 设置颜色
graphics.setColor(new Color(random.nextInt(colorRandoMax
- colorRandoMin + 1)
+ colorRandoMin, random.nextInt(colorRandoMax - colorRandoMin
+ 1)
+ colorRandoMin, random.nextInt(colorRandoMax - colorRandoMin
+ 1)
+ colorRandoMin));
// 填充矩形
graphics.fillRect(0, 0, 68, 23);
// 绘制文字
char[] valChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
.toCharArray();
// 索引
int index = 0;
int len = valChar.length;
// 用来拼接字符存储进session
StringBuilder sb = new StringBuilder();
// 重设文字颜色范围
colorRandoMin = 1;
colorRandoMax = 130;
// 生成4个字符
for (int i = 0; i < 4; i++) {
// 生成索引
index = random.nextInt(len);
graphics.setFont(new Font("Arial", Font.BOLD, 16));
// 设置文字颜色
graphics.setColor(new Color(random.nextInt(colorRandoMax
- colorRandoMin + 1)
+ colorRandoMin, random.nextInt(colorRandoMax
- colorRandoMin + 1)
+ colorRandoMin, random.nextInt(colorRandoMax
- colorRandoMin + 1)
+ colorRandoMin));
// 绘制文字
graphics.drawString(valChar[index] + "", i * 15 + 5, 18);
sb.append(valChar[index]);
}
// 存储在session中
request.getSession().setAttribute("validateCode", sb.toString());
sb = null;
// 输入验证码图
OutputStream out = response.getOutputStream();
ImageIO.write(bufferedImage, "jpg", out);
// 刷新并关闭输出流
out.flush();
out.close();
}