<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="java.util.Random"%>
<%@ page import="java.awt.image.BufferedImage"%>
<%@ page import="java.awt.Color,java.awt.Graphics,java.awt.Font"%>
<%@ page import="javax.imageio.ImageIO"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>验证码</title>
</head>
<body>
<%!
// 根据给定范围生成随机颜色
Color getRandColor(int beginColor, int endColor) {
Random random = new Random();
if (beginColor > 255) {
beginColor = 255;
}
if (endColor > 255) {
endColor = 255;
}
int r = beginColor + random.nextInt(endColor - beginColor);
int g = beginColor + random.nextInt(endColor - beginColor);
int b = beginColor + random.nextInt(endColor - beginColor);
return new Color(r, g, b);
}
%>
<%
String chars =
"123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// 设置响应的内容类型
response.setContentType("image/jpeg");
// 设置页面不缓存
response.addHeader("pragma", "NO-cache");
response.addHeader("Cache-Control", "no-cache");
response.addDateHeader("Expries", 0);
// 在内存中创建图象
int width = 65, height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 创建一个 Graphics2D 对象,可以将它绘制到此 BufferedImage 中
Graphics g = image.createGraphics();
// 将此图形上下文的当前颜色设置为指定颜色
g.setColor(new Color(51, 102, 255));
// 填充矩形
g.fillRect(0, 0, width, height);
Random rand = new Random();
// 随机产生很多条干扰线,使图像中的验证码不易被其它程序探测到
for (int i = 0; i < 50; i++) {
g.setColor(getRandColor(100, 150));
int x = rand.nextInt(width);
int y = rand.nextInt(height);
int xl = rand.nextInt(10);
int yl = rand.nextInt(10);
g.drawLine(x, y, x + xl, y + yl);
}
//设置字体
g.setFont(new Font("Times New Roman", Font.BOLD + Font.ITALIC, 16));
//设置字体颜色
g.setColor(Color.WHITE);
// 取随机产生的验证码(4位数字)
String sRand = "";
for (int i = 0; i < 4; i++) {
String ranChar = String.valueOf(chars.charAt(rand.nextInt(chars.
length())));
sRand += ranChar;
// 使用此图形上下文的当前字体和颜色绘制由指定 string 给定的文本
g.drawString(ranChar, 14 * i + 6, 15);
}
// 将产生的验证码保存在会话
session.setAttribute("picCode", String.valueOf(sRand.toLowerCase()));
// 释放此图形的上下文以及它使用的所有系统资源
g.dispose();
// 将图像输出到客户端
ServletOutputStream sos = response.getOutputStream();
ImageIO.write(image, "jpeg", sos);
sos.close();
out.clear();
out = pageContext.pushBody();
%>
</body>
</html>