int codeCount = 4;
//int codeSequence[] = null;
// 随机产生codeCount数字的验证码。
// for (int i = 0; i < codeCount; i++) {
// // 得到随机产生的验证码数字。
// String strRand = String.valueOf(random.nextInt(9));
// // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
// red = random.nextInt(255);
// green = random.nextInt(255);
// blue = random.nextInt(255);
//
// // 用随机产生的颜色将验证码绘制到图像中。
// g.setColor(new Color(red, green, blue));
// int codeY = 50;
// int x = 20;
// g.drawString(strRand, (i) * x + 5, codeY);
//
// // 将产生的四个随机数组合在一起。
// randomCode.append(strRand);
// }
// 将四位数字的验证码保存到Session中。
HttpSession session = req.getSession(true);
g.drawString((String) session.getAttribute("validateCode"), 3 * 20 + 5, 50);
//session.setAttribute("validateCode", randomCode.toString());
System.out.println(String.valueOf((session.getAttribute("validateCode"))));
// 禁止图像缓存。
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 0);
resp.setContentType("image/jpeg");
// 将图像输出到Servlet输出流中。
ServletOutputStream sos = resp.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
}
把验证码放在JSP页面生成。传入servlet.然后由servlet生成图片输出