首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 生成驗證碼圖片(非二維碼):Servlet 輸出圖流 + 前端點擊刷新完整實現

     編輯:Java 綜合教學

說明:本文實現的是「圖形驗證碼」,而非二維碼

代碼邏輯:隨機生成 4 位字符,繪製干擾線,輸出 PNG 流,存入 Session,前端 <img> 標簽直接請求 Servlet 地址。

後端 Servlet 核心代碼

  1. @RequestMapping("/captcha.html")
  2. public void captcha(HttpServletResponse response, HttpServletRequest request) throws Exception {
  3. response.setContentType("image/png");
  4. response.setHeader("Pragma", "No-cache");
  5. response.setHeader("Cache-Control", "no-cache");
  6. response.setDateHeader("Expires", 0);
  7. int width = 80, height = 40;
  8. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  9. Graphics g = image.getGraphics();
  10. // 背景
  11. g.setColor(new Color(40, 200, 255));
  12. g.fillRect(0, 0, width, height);
  13. // 隨機字符池
  14. char[] chars = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890".toCharArray();
  15. Random random = new Random();
  16. StringBuilder code = new StringBuilder();
  17. // 繪製 4 個字符
  18. for (int i = 0; i < 4; i++) {
  19. char ch = chars[random.nextInt(chars.length)];
  20. g.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
  21. g.setFont(new Font("微軟雅黑", Font.BOLD, 18));
  22. g.drawString(String.valueOf(ch), i * 15 + 3, 18);
  23. code.append(ch);
  24. }
  25. // 干擾線
  26. for (int i = 0; i < 20; i++) {
  27. g.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
  28. g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
  29. }
  30. g.dispose();
  31. // 存入 Session
  32. request.getSession().setAttribute("captcha_code", code.toString());
  33. // 輸出圖片流
  34. ImageIO.write(image, "png", response.getOutputStream());
  35. }

前端頁面集成

  1. <img id="captchaImg" src="${pageContext.request.contextPath}/captcha.html" style="cursor:pointer;" title="點擊刷新" />
  2. <script>
  3. document.getElementById('captchaImg').onclick = function() {
  4. this.src = '${pageContext.request.contextPath}/captcha.html?' + new Date().getTime();
  5. };
  6. </script>

關鍵點解析

  1. 防緩存:響應頭 Pragma/No-cache、Cache-Control/no-cache、Expires=0,加隨機時間戳參數強制瀏覽器重新請求。
  2. Session 綁定:驗證碼碼值存 Session,表單提交時後端比對 session.getAttribute("captcha_code")。
  3. 字體可用性:Linux 服務器需安裝中文字體(如 yum install fontconfig mkfontscale 並拷貝 msyh.ttc),否則中文顯示為方塊。
  4. 干擾線數量:示例 20 條足夠,原代碼 10000 條極其消耗 CPU,已優化。

驗證邏輯(Controller 片段)

  1. @PostMapping("/login")
  2. public String login(@RequestParam String captcha, HttpSession session) {
  3. String real = (String) session.getAttribute("captcha_code");
  4. if (real == null || !real.equalsIgnoreCase(captcha)) {
  5. return "驗證碼錯誤";
  6. }
  7. // 校驗通過,清除驗證碼防重用
  8. session.removeAttribute("captcha_code");
  9. return "登入成功";
  10. }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved