“原生 js + SpringBoot + hutool 工具” 实现浏览器验证码功能,点击可刷新。
文章目录
- 
- 一、理解 “ 服务器 / 浏览器 ”沟通流程(3步)
 - 二、开发前准备:
 - 三、 代码实现
 - 四、“点击验证码图片自动刷新” 是如何实现的 ?
 - 五、最终效果
 
 
一、理解 “ 服务器 / 浏览器 ”沟通流程(3步)
- 第1步:浏览器使用
<img src="/test/controller”>标签请求特定 Controller 路径。 - 第2步:服务器 Controller 返回图片的二进制数据。
 - 第3步:浏览器接收到数据,显示图片。
 

二、开发前准备:
- Spring Boot开发常识
 - hutool工具(hutool是一款Java辅助开发工具,利用它可以快速生成验证码图片,从而避免让我们编写大量重复代码,具体使用请移至官网)
 
<!-- pom 导包:hutool 工具 -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-captcha</artifactId>
    <version>5.8.5</version>
</dependency>
三、 代码实现
【 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);
      	// 将验证码图片的二进制数据写入【响应体 response 】
        captcha.write(response.getOutputStream());
    }
}
四、“点击验证码图片自动刷新” 是如何实现的 ?
  HTML 规范规定,在 <img src=“xxx”> 标签中,每当 src 路径发生变化时,浏览器就会自动重新请求资源。所以我们可以编写一个简单的 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>
五、最终效果

相关文章
暂无评论...
