圖片驗證碼是阻擋機器人自動註冊、暴力破解最常見的手段。Java 的 java.awt 與 ImageIO 就足以完成畫布、字體、干擾線與輸出,不需要額外相依套件。本文示範一個可設定寬高、字元數與干擾線數的驗證碼產生器,並包裝成 Servlet 直接輸出圖片。
package com.rchm.util.images;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* 驗證碼產生器
*/
public class ValidateCode {
private int width = 160; // 圖片寬度
private int height = 40; // 圖片高度
private int codeCount = 5; // 驗證碼字元個數
private int lineCount = 150; // 干擾線數量
private static String code = null; // 驗證碼本體
private BufferedImage buffImg = null; // 圖片緩衝
private char[] codeSequence = {
'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
'P','Q','R','S','T','U','V','W','X','Y','Z',
'1','2','3','4','5','6','7','8','9'
};
public ValidateCode() {
this.createCode();
}
public ValidateCode(int width, int height) {
this.width = width;
this.height = height;
this.createCode();
}
public ValidateCode(int width, int height, int codeCount, int lineCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
this.lineCount = lineCount;
this.createCode();
}
public void createCode() {
int x = width / (codeCount + 2); // 每個字元的間距
int fontHeight = height - 2; // 字體高度
int codeY = height - 4; // 基準線
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
Random random = new Random();
// 底色填白
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 設定字體
ImgFontByte imgFont = new ImgFontByte();
Font font = imgFont.getFont(fontHeight);
g.setFont(font);
// 畫出隨機顏色的干擾線
for (int i = 0; i < lineCount; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs + random.nextInt(width / 8);
int ye = ys + random.nextInt(height / 8);
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.drawLine(xs, ys, xe, ye);
}
// 產生 codeCount 個隨機字元
StringBuffer randomCode = new StringBuffer();
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.drawString(strRand, (i + 1) * x, codeY);
randomCode.append(strRand);
}
code = randomCode.toString();
g.dispose();
}
public void write(String path) throws IOException {
OutputStream sos = new FileOutputStream(path);
this.write(sos);
}
public void write(OutputStream sos) throws IOException {
ImageIO.write(buffImg, "png", sos);
sos.close();
}
public BufferedImage getBuffImg() {
return buffImg;
}
public static String getCode() {
return code;
}
}
package com.rchm.util.images;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ValidateCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/jpeg");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
ValidateCode vCode = new ValidateCode(100, 30, 4, 100);
HttpSession session = request.getSession();
session.removeAttribute("validateCode");
session.setAttribute("validateCode", vCode.getCode());
vCode.write(response.getOutputStream()); // 只輸出一次即可
}
}
<servlet> <servlet-name>validateCodeServlet</servlet-name> <servlet-class>com.rchm.util.images.ValidateCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>validateCodeServlet</servlet-name> <url-pattern>/validateCodeServlet</url-pattern> </servlet-mapping>
驗證碼的正確值必須存進 session,表單送出時再取出比對,比對成功後應該立即從 session 移除,避免被重複使用。
字元集刻意排除了容易混淆的 O/0、I/1、Z/2 等組合,使用者辨識錯誤率會明顯下降。
另外,單靠圖片驗證碼已被 OCR 大量破解,高安全需求的網站建議改用行為驗證、加點驗證或第三方 CAPTCHA 服務;同時別忘了加上「同一 IP/Session 的嘗試次數限制」,這往往比驗證碼本身更有效。