亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot+hutool實現(xiàn)圖片驗證碼

 更新時間:2022年08月16日 16:54:05   作者:ThinkStu  
本文主要介紹了SpringBoot+hutool實現(xiàn)圖片驗證碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

一、理解 “ 服務器 / 瀏覽器 ”溝通流程(3步)

第1步:瀏覽器使用<img src="/test/controller”>標簽請求特定 Controller 路徑。

第2步:服務器 Controller 返回圖片的二進制數(shù)據(jù)。

第3步:瀏覽器接收到數(shù)據(jù),顯示圖片。

二、開發(fā)前準備:

Spring Boot開發(fā)常識

hutool工具(hutool是一款Java輔助開發(fā)工具,利用它可以快速生成驗證碼圖片,從而避免讓我們編寫大量重復代碼,具體使用請移至官網(wǎng))

<!-- pom 導包:hutool 工具 -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-captcha</artifactId>
    <version>5.8.5</version>
</dependency>

三、 代碼實現(xiàn)

【 index.html 】頁面

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>驗證碼頁面</title>
</head>
<body>
  
<form action="#" method="post">
  
  	<!-- img標簽負責向服務器 Controller 請求圖片資源 -->
    <img src="/test/code" id="code" onclick="refresh();">
  
</form>
  
</body>

<!-- “點擊驗證碼圖片,自動刷新” 腳本 -->
<script>
    function refresh() {
        document.getElementById("code").src = 
          "/test/code?time" + new Date().getTime();
    }
</script>
</html>

【SpringBoot后端】

@RestController
@RequestMapping("test")
public class TestController {
  
    @Autowired
    HttpServletResponse response;
    @Autowired
    HttpSession session;

    @GetMapping("code")
    void getCode() throws IOException {
   		  // 利用 hutool 工具,生成驗證碼圖片資源
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 5);
        // 獲得生成的驗證碼字符
        String code = captcha.getCode();
        // 利用 session 來存儲驗證碼
        session.setAttribute("code",code);
      	// 將驗證碼圖片的二進制數(shù)據(jù)寫入【響應體 response 】
        captcha.write(response.getOutputStream());
    }
}

四、“點擊驗證碼圖片自動刷新” 是如何實現(xiàn)的 ?

HTML 規(guī)范規(guī)定,在 <img src=“xxx”> 標簽中,每當 src 路徑發(fā)生變化時,瀏覽器就會自動重新請求資源。所以我們可以編寫一個簡單的 js 腳本,只要驗證碼圖片被點擊,src 路徑就會被加上當前【時間戳】,從而達到改變 src 路徑的目的。

 <img src="/test/code" id="code" onclick="refresh();">

......

<!-- “點擊驗證碼圖片,自動刷新” 腳本 -->
<script>
    function refresh() {
        document.getElementById("code").src = 
          "/test/code?time" + new Date().getTime();
    }
</script>

五、最終效果

 到此這篇關(guān)于SpringBoot+hutool實現(xiàn)圖片驗證碼的文章就介紹到這了,更多相關(guān)SpringBoot 圖片驗證碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論