圖片驗證碼(CAPTCHA)是網站常見的安全機制,主要用於 區分真人用戶與自動化腳本,提升系統安全性。其核心邏輯是:伺服器生成包含隨機字符的圖片,用戶需正確輸入圖片上的文字才能通過驗證,從而防止暴力破解、機器人註冊、垃圾留言等惡意行為。
實作圖片驗證碼主要用到 Java 圖形處理相關的兩個關鍵類:
BufferedImage:在記憶體中建立圖片物件ImageIO:將圖片輸出為指定格式(如 JPG)// 建立 60x20 像素的 RGB 圖片 BufferedImage im = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB); // 將圖片以 JPG 格式輸出到回應流,瀏覽器即可直接顯示 ImageIO.write(im, "JPG", response.getOutputStream());
BufferedImage im = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB); ImageIO.write(im, "JPG", response.getOutputStream());
Graphics g = im.getGraphics();
Random rm = new Random(); Color c = new Color(rm.nextInt(255), rm.nextInt(255), rm.nextInt(255)); g.setColor(c); g.fillRect(0, 0, 60, 20);
g.setColor(new Color(rm.nextInt(255), rm.nextInt(255), rm.nextInt(255)));
g.setFont(new Font("華文隸書", Font.BOLD | Font.ITALIC, 28));
g.drawString("8", 1, 18);
for (int i = 0; i < 4; i++) {
g.setColor(new Color(rm.nextInt(255), rm.nextInt(255), rm.nextInt(255)));
g.setFont(new Font("Gungsuh", Font.BOLD | Font.ITALIC, 22));
g.drawString("" + rm.nextInt(10), (i * 15) + 2, 18);
}
String str = "胸有激雷而面如平湖者可拜上將軍";
for (int i = 0; i < 4; i++) {
g.setColor(new Color(rm.nextInt(255), rm.nextInt(255), rm.nextInt(255)));
g.setFont(new Font("Gungsuh", Font.BOLD | Font.ITALIC, 15));
g.drawString("" + str.charAt(rm.nextInt(str.length())), (i * 15) + 2, 18);
}
在 JSP/HTML 中直接用 <img> 標籤指向生成驗證碼的 Servlet:
<img alt="驗證碼" src="/ImageServlet">
// 假設 sbf 是 StringBuilder,已拼湊好 4 位驗證碼
request.getSession().setAttribute("piccode", sbf.toString());
// 先驗證用戶是否存在
boolean b_exist = login.validate(username, passwd);
if (b_exist) {
// 從 Session 取出正確驗證碼
String pic = "" + request.getSession().getAttribute("piccode");
// 比對用戶輸入
if (!pic.equals("") && pic.equals(code)) {
// 驗證通過,存入用戶資訊並導向首頁
request.getSession().setAttribute("username", username);
response.sendRedirect("index.jsp");
}
}
將上述邏輯封裝在一個 Servlet 中,配置好 web.xml 映射路徑即可使用。建議加入干擾線、噪點等進階功能以提高安全性。