关于产生一个一次性验证码的代码如下
public class CheckImgServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int width = 120;
int height = 30;
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
graphics.setColor(getRandColor(200, 250));
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.WHITE);
graphics.drawRect(0, 0, width - 1, height - 1);
Graphics2D graphics2d = (Graphics2D) graphics;
graphics2d.setFont(new Font("瀹嬩綋", Font.BOLD, 18));
String words =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
Random random = new Random();
StringBuffer buffer = new StringBuffer();
int x = 10;
for (int i = 0; i < 4; i++) {
graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
// 鏃嬭浆 -30 --- 30搴�
int jiaodu = random.nextInt(60) - 30;
// 鎹㈢畻寮у害
double theta = jiaodu * Math.PI / 180;
// 鐢熸垚涓�涓殢鏈烘暟瀛�
int index = random.nextInt(words.length()); // 鐢熸垚闅忔満鏁� 0 鍒� length - 1
// 鑾峰緱瀛楁瘝鏁板瓧
char c = words.charAt(index);
// 灏嗛殢鏈轰骇鐢熺殑瀛楃瀛樺叆鍒板瓧绗︿覆涓�:
buffer.append(c);
// 灏哻 杈撳嚭鍒板浘鐗�
graphics2d.rotate(theta, x, 20);
graphics2d.drawString(String.valueOf(c), x, 20);
graphics2d.rotate(-theta, x, 20);
x += 30;
}
// 灏哹uffer杞垚瀛楃涓插璞★細
String checkcode = buffer.toString();
// 灏嗗叾瀛樺叆鍒皊ession涓�
request.getSession().setAttribute("checkcode", checkcode);
// 姝ラ浜� 缁樺埗骞叉壈绾�
graphics.setColor(getRandColor(160, 200));
int x1;
int x2;
int y1;
int y2;
for (int i = 0; i < 30; i++) {
x1 = random.nextInt(width);
x2 = random.nextInt(12);
y1 = random.nextInt(height);
y2 = random.nextInt(12);
graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
}
// 灏嗕笂闈㈠浘鐗囪緭鍑哄埌娴忚鍣� ImageIO
graphics.dispose();// 閲婃斁璧勬簮
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
private Color getRandColor(int fc, int bc) {
// 鍙栧叾闅忔満棰滆壊
Random random = new Random();
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}