萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JSP 實作隨機圖形驗證碼:Servlet + AWT 完整範例

驗證碼設計原理

  • 伺服器生成隨機字串,存入 Session
  • 以圖片形式輸出(含干擾線、字體扭曲、隨機色彩)
  • 用戶提交時比對 Session 值,防止自動化腳本

ValidateCodeServlet 完整實作

package com.servlet;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;

public class ValidateCodeServlet extends HttpServlet {
    private int width = 60, height = 20, codeCount = 4;
    private int x, fontHeight, codeY;
    private char[] codeSequence = {
        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T',
        'U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'
    };

    public void init() throws ServletException {
        // 從 web.xml 讀取初始化參數
        String w = getInitParameter("width");
        String h = getInitParameter("height");
        String c = getInitParameter("codeCount");
        if (w != null) width = Integer.parseInt(w);
        if (h != null) height = Integer.parseInt(h);
        if (c != null) codeCount = Integer.parseInt(c);

        x = width / (codeCount + 1);
        fontHeight = height - 2;
        codeY = height - 4;
    }

    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = img.createGraphics();
        Random rand = new Random();

        // 背景
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 字體
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
        g.setFont(font);

        // 邊框
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);

        // 160 條干擾線
        g.setColor(Color.BLACK);
        for (int i = 0; i < 160; i++) {
            int x = rand.nextInt(width);
            int y = rand.nextInt(height);
            int xl = rand.nextInt(12);
            int yl = rand.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }

        // 生成驗證碼
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < codeCount; i++) {
            String ch = String.valueOf(codeSequence[rand.nextInt(36)]);
            int r = rand.nextInt(255), g_ = rand.nextInt(255), b = rand.nextInt(255);
            g.setColor(new Color(r, g_, b));
            g.drawString(ch, (i + 1) * x, codeY);
            code.append(ch);
        }

        // 存入 Session
        HttpSession session = req.getSession();
        session.setAttribute("validateCode", code.toString());

        // 禁止快取
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        resp.setContentType("image/jpeg");

        // 輸出
        ImageIO.write(img, "jpeg", resp.getOutputStream());
    }
}

web.xml 註冊配置

<servlet>
    <servlet-name>ValidateCodeServlet</servlet-name>
    <servlet-class>com.servlet.ValidateCodeServlet</servlet-class>
    <init-param><param-name>width</param-name><param-value>200</param-value></init-param>
    <init-param><param-name>height</param-name><param-value>80</param-value></init-param>
    <init-param><param-name>codeCount</param-name><param-value>5</param-value></init-param>
</servlet>
<servlet-mapping>
    <servlet-name>ValidateCodeServlet</servlet-name>
    <url-pattern>/validateCodeServlet</url-pattern>
</servlet-mapping>

前端頁面引用

<img src="validateCodeServlet" width="100" height="40" 
     onclick="this.src='validateCodeServlet?'+Math.random()" 
     title="點擊更換" style="cursor:pointer; vertical-align:middle">
<input type="text" name="validateCode" maxlength="5">

後端驗證邏輯

String inputCode = request.getParameter("validateCode");
String sessionCode = (String) session.getAttribute("validateCode");
if (sessionCode != null && sessionCode.equalsIgnoreCase(inputCode)) {
    // 驗證通過
} else {
    // 驗證失敗
}

增強安全性建議

  • 字元集擴充:加入中文、特殊符號
  • 字體扭曲:AffineTransform 仿射變換
  • 噪點/干擾圓:g.fillOval() 隨機繪製
  • Session 存儲加密:HMAC 或加密存儲,防 Session 劫持
  • 限制嘗試次數:超過 N 次鎖定/要求重新獲取
  • 考慮現代替代:reCAPTCHA、hCaptcha、滑塊驗證、行為分析
copyright © 萬盛學電腦網 all rights reserved