首页 > 编程技术 > java

SpringBoot+hutool实现图片验证码

发布时间:2022-8-17 07:16 作者:ThinkStu

一、理解 “ 服务器 / 浏览器 ”沟通流程(3步)

第1步:浏览器使用<img" width=100% 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" width=100% 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" width=100% src=“xxx”> 标签中,每当 src 路径发生变化时,浏览器就会自动重新请求资源。所以我们可以编写一个简单的 js 脚本,只要验证码图片被点击,src 路径就会被加上当前【时间戳】,从而达到改变 src 路径的目的。

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

......

<!-- “点击验证码图片,自动刷新” 脚本 -->
<script>
    function refresh() {
        document.getElementById("code").src = 
          "/test/code?time" + new Date().getTime();
    }
</script>

五、最终效果

 到此这篇关于SpringBoot+hutool实现图片验证码的文章就介绍到这了,更多相关SpringBoot 图片验证码内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.csdn.net/qq_35760825/article/details/126308778

标签:[!--infotagslink--]

您可能感兴趣的文章: