生成 60×20 像素 JPEG 圖片,包含 4 位隨機數字、155 條干擾線、隨機背景色與字體色,每次請求刷新(含瀏覽器後退)。
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%
// 禁止緩存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 1. 創建畫布
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
// 2. 繪製背景
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 3. 設置字體
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
// 4. 繪製干擾線
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// 5. 生成並繪製 4 位驗證碼
StringBuilder sRand = new StringBuilder();
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand.append(rand);
// 隨機字體顏色
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
// 6. 存入 Session
session.setAttribute("rand", sRand.toString());
// 7. 輸出圖片
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
%>
<%!
// 取隨機顏色輔助方法
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);
}
%>
<form method="post" action="check.jsp">
<table>
<tr><td>系統產生的驗證碼:</td>
<td><img src="image.jsp" onclick="this.src='image.jsp?'+Math.random()" style="cursor:pointer" title="點擊刷新"></td></tr>
<tr><td>輸入驗證碼:</td>
<td><input type="text" name="rand" maxlength="4" required></td></tr>
<tr><td colspan="2"><input type="submit" value="提交驗證"></td></tr>
</table>
</form>
關鍵點:`` 添加 `onclick` 刷新,防止瀏覽器緩存圖片導致驗證碼不更新。
<%
String rand = (String) session.getAttribute("rand");
String input = request.getParameter("rand");
%>
系統生成:<%= rand %><br>
用戶輸入:<%= input %><br>
<%
if (rand != null && rand.equalsIgnoreCase(input)) {
out.println("<font color='green'>驗證成功!</font>");
} else {
out.println("<font color='red'>驗證失敗!</font>");
}
%>
/api/captcha 返回 {imageBase64, uuid},前端展示;驗證時攜帶 uuid 校驗 Redis 中存儲的值(設置 5 分鐘過期),避免 Session 依賴。