核心組件:`ValidateCode` (圖片生成邏輯) + `ValidateCodeServlet` (HTTP 端點) + `web.xml` 配置。適用於登錄、註冊、表單提交等防機器人場景。
package com.rchm.util.images;
import java.awt.*;
import java.awt.image.BufferedImage;
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 = 4;
private int lineCount = 50; // 干擾線數量 (原文 150 過多影響識別)
private String code = null;
private BufferedImage buffImg = null;
// 字符集:排除易混淆字符 (0/O, 1/I/l, 2/Z 等)
private final char[] codeSequence = {
'A','B','C','D','E','F','G','H','J','K','M','N','P','Q','R','S','T','U','V','W','X','Y',
'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();
}
private void createCode() {
int x = width / (codeCount + 2); // 每字符寬度
int fontHeight = height - 4; // 字體高度
int codeY = height - 6; // 文字基線 Y
// 1. 創建圖像緩衝區
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 2. 填充背景 (淺色隨機)
g.setColor(getRandomLightColor());
g.fillRect(0, 0, width, height);
// 3. 繪製干擾線
Random random = new Random();
for (int i = 0; i < lineCount; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs + random.nextInt(width / 5);
int ye = ys + random.nextInt(height / 5);
g.setColor(getRandomColor(160, 200));
g.drawLine(xs, ys, xe, ye);
}
// 4. 設置字體 (抗鋸齒)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setFont(new Font("Fixedsys", Font.BOLD, fontHeight));
// 5. 繪製驗證碼字符
StringBuilder randomCode = new StringBuilder();
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
randomCode.append(strRand);
// 隨機顏色、隨機旋轉、隨機位置微調
g.setColor(getRandomColor(20, 130));
// 簡單旋轉效果 (可選)
// g.rotate(Math.random() * 0.3 - 0.15, (i+1)*x, codeY);
g.drawString(strRand, (i + 1) * x, codeY);
// g.rotate(-(Math.random() * 0.3 - 0.15), (i+1)*x, codeY);
}
code = randomCode.toString();
g.dispose(); // 釋放圖形資源
}
// 輔助:隨機深色 (文字用)
private Color getRandomColor(int min, int max) {
Random r = new Random();
return new Color(r.nextInt(max - min) + min,
r.nextInt(max - min) + min,
r.nextInt(max - min) + min);
}
// 輔助:隨機淺色 (背景用)
private Color getRandomLightColor() {
Random r = new Random();
return new Color(200 + r.nextInt(55), 200 + r.nextInt(55), 200 + r.nextInt(55));
}
// 輸出流
public void write(OutputStream sos) throws IOException {
ImageIO.write(buffImg, "PNG", sos); // PNG 無損,比 JPEG 適合驗證碼
sos.flush();
}
public BufferedImage getBuffImg() { return buffImg; }
public String getCode() { return code; }
}
package com.rchm.util.images;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class ValidateCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 1. 設置響應頭:禁止緩存,關鍵!
resp.setContentType("image/png");
resp.setHeader("Pragma", "No-cache");
resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
resp.setDateHeader("Expires", 0);
// 2. 生成驗證碼 (可配置參數)
ValidateCode vCode = new ValidateCode(120, 40, 4, 30);
// 3. 存入 Session (key 統一常量)
HttpSession session = req.getSession();
session.setAttribute("VALIDATE_CODE", vCode.getCode().toLowerCase()); // 統一小寫比對
// 4. 輸出圖片
vCode.write(resp.getOutputStream());
}
}
<servlet>
<servlet-name>validateCodeServlet</servlet-name>
<servlet-class>com.rchm.util.images.ValidateCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
validateCodeServlet
/captcha.jpg
</servlet-mapping>
<img id="captchaImg" src="/captcha.jpg?t=" + Date.now()
onclick="this.src='/captcha.jpg?t='+Date.now()"
style="cursor:pointer;vertical-align:middle"
title="點擊刷新">
<input type="text" name="captcha" placeholder="輸入驗證碼" maxlength="4">
@PostMapping("/login")
public Result login(@RequestParam String username,
@RequestParam String password,
@RequestParam String captcha,
HttpSession session) {
String realCode = (String) session.getAttribute("VALIDATE_CODE");
if (realCode == null || !realCode.equals(captcha.toLowerCase())) {
return Result.error("驗證碼錯誤或已過期");
}
session.removeAttribute("VALIDATE_CODE"); // 一次性使用
// ... 後續業務邏輯
}
| 風險 | 對策 |
|---|---|
| 暴力破解 | 限制同 IP/Session 請求頻率 (如 5 次/分鐘),失敗鎖定 |
| 驗證碼復用 | 驗證後立即 `session.removeAttribute`,一次性失效 |
| 圖片緩存 | 響應頭 `Cache-Control: no-store` + URL 加隨機參數 |
| OCR 識別 | 增加干擾線、字符旋轉、噪點、扭曲、背景幹擾 |
| CSRF | 表單添加 CSRF Token,驗證碼不替代 CSRF 防護 |
| 會話固定 | 登錄成功後 `session.invalidate()` 重建 Session |
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 圖片驗證碼 (本文) | 無第三方依賴、完全可控、部署簡單 | 用戶體驗差、OCR 可破解、無障礙差 | 內部系統、低風險表單 |
| 滑動/點選/圖標驗證 | 體驗好、機器成本高 | 需前端 SDK、移動端適配複雜 | 高並發、用戶面產品 |
| reCAPTCHA / Turnstile | 安全性極高、無感驗證 | 依賴外網、隱私合規、中國大陸訪問慢 | 國際化產品、高安全需求 |
| 設備指紋 + 行為分析 | 無感、持續驗證 | 實現複雜、誤判風險 | 高級風控系統 |
Java 圖片驗證碼實現核心在於:`BufferedImage` 繪圖、隨機字符集、干擾線/噪點、抗鋸齒渲染、無緩存輸出、Session 綁定一次性驗證。生產環境建議:參數化配置、字符集去混淆、添加字符旋轉扭曲、接入限流熔斷、考慮無障礙替代方案 (音頻驗證碼)。