SpringBoot如何生成验证码呢?
下文笔者讲述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());
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


