萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 實現彩色驗證碼:動態生成干擾線、隨機顏色、Session 驗證全流程

效果預覽

生成 60×20 像素 JPEG 圖片,包含 4 位隨機數字、155 條干擾線、隨機背景色與字體色,每次請求刷新(含瀏覽器後退)。

核心文件:image.jsp

<%@ 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);
}
%>

前端調用頁:a.jsp

<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` 刷新,防止瀏覽器緩存圖片導致驗證碼不更新。

驗證頁:check.jsp

<%
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>");
}
%>

安全增強建議

  • 字符集擴展:數字 + 大小寫字母,排除易混淆字符(0/O, 1/I/l)。
  • 增加扭曲、噪點、幹擾圓弧,對抗 OCR 識別。
  • 引入成熟庫:Kaptcha、SimpleCaptcha、Hutool CaptchaUtil,一行代碼生成高強度驗證碼。
  • 前後端分離架構下:後端提供 /api/captcha 返回 {imageBase64, uuid},前端展示;驗證時攜帶 uuid 校驗 Redis 中存儲的值(設置 5 分鐘過期),避免 Session 依賴。
copyright © 萬盛學電腦網 all rights reserved