/**
* <校验码>
*
* @param request
* @param response
* @throws IOException
* @author Administrator
* @date 2010-5-12
*/
private void verifyCode(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
HttpSession session = request.getSession();
// 在内存中创建图象
int width = 60, height = 18;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 设定背景色
g.setColor(new Color(0xffffff));
g.fillRect(0, 0, width, height);
String mapTable[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
StringBuffer rands = new StringBuffer();
Random ran = new Random();
for (int i = 0; i < 4; ++i) {
rands.append(mapTable[ran.nextInt(mapTable.length)]);
}
String rand = rands.toString();
// 将认证码存入SESSION
session.setAttribute("rand", rand);
// 将认证码显示到图象中
g.setColor(Color.black);
g.setFont(new Font("Times New Roman", Font.BOLD, 16));
String Str = rand.substring(0, 1);
g.drawString(Str, 13 * 0 + 6, 12);
Str = rand.substring(1, 2);
g.drawString(Str, 13 * 1 + 6, 17);
Str = rand.substring(2, 3);
g.drawString(Str, 13 * 2 + 6, 15);
Str = rand.substring(3, 4);
g.drawString(Str, 13 * 3 + 6, 15);
// Str = rand.substring(4,5);
// g.drawString(Str,65,15);
// 随机产生88个干扰点,使图象中的认证码不易被其它程序探测到
Random random = new Random();
for (int i = 0; i < 3; i++) {
Color c5 = new Color(random.nextInt(200), random.nextInt(200),
random.nextInt(200));
g.setColor(c5);
int x = random.nextInt(width / 2);
int y = random.nextInt(height / 2);
int xl = random.nextInt(60);
int yl = random.nextInt(20);
g.drawLine(x, y, x + xl, y + yl);
}
// Random random = new Random();
for (int i = 0; i < 68; i++) {
Color c6 = new Color(random.nextInt(250), random.nextInt(250),
random.nextInt(200));
g.setColor(c6);
int x = random.nextInt(width);
int y = random.nextInt(height);
g.drawOval(x, y, 0, 0);
}
// 图象生效
g.dispose();
// 输出图象到页面
ServletOutputStream responseOutputStream = response.getOutputStream();
// 输出图象到页面
ImageIO.write(image, "JPEG", responseOutputStream);
// 以下关闭输入流!
responseOutputStream.flush();
responseOutputStream.close();
image = null;
}
校验码
最新推荐文章于 2024-04-06 16:42:06 发布