“原生 js + SpringBoot + hutool 工具” 实现浏览器验证码功能,点击可刷新。
二、开发前准备:
- Spring Boot开发常识
- hutool工具(hutool是一款Java辅助开发工具,利用它可以快速生成验证码图片,从而避免让我们编写大量重复代码,具体使用请移至官网)
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-captchaartifactId>
<version>5.8.5version>
dependency>
- 1
- 2
- 3
- 4
- 5
- 6
三、 代码实现
【 index.html 】页面
DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>验证码页面title>
head>
<body>
<form action="#" method="post">
<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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
【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());
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
四、“点击验证码图片自动刷新” 是如何实现的 ?
HTML 规范规定,在 
标签中,每当 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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
五、最终效果
