驗證碼(CAPTCHA)廣泛應用於用戶註冊、登入、發文等場景,防止自動化腳本濫用。核心原理:伺服器隨機生成字串,繪製成干擾線、扭曲字體的圖片,存入 Session;用戶提交時比對輸入值與 Session 值,一致才通過。
<%@ page contentType="image/jpeg"
import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
// 取得隨機顏色
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);
}
%>
<%
// 禁止快取
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
int width = 80, height = 30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
// 背景填充
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 字體設定
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
// 畫干擾線
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);
}
// 產生 4 位隨機數字
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110),
20 + random.nextInt(110),
20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
// 存入 Session
session.setAttribute("rand", sRand);
// 輸出圖片
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
session.setAttribute("rand", sRand),驗證時從 Session 取出比對。<img src="Num.jsp" id="captchaImg" onclick="this.src='Num.jsp?'+Math.random()" />
<input type="text" name="captcha" />
點擊圖片切換 src 加隨機參數,強制瀏覽器重新請求新驗證碼。
String input = request.getParameter("captcha");
String real = (String) session.getAttribute("rand");
if (real != null && real.equalsIgnoreCase(input)) {
// 驗證通過
} else {
// 驗證失敗
}
Kaptcha、SimpleCaptcha、Google reCAPTCHA)替代手寫實作。