SpringBoot如何生成验证码呢?

乔欣 SpringBoot 发布时间:2023-03-06 10:05:40 阅读数:2125 1
下文笔者讲述SpringBoot生成验证码的方法分享,如下所示

SpringBoot验证码生成方法

实现思路:
    1.使用SpringBoot和hutool工具--生成验证码数据流
    2.使用js调用--验证码数据流
例:
 
//引入 hutool依赖
<!-- 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());
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202303/5963.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者