看我代码直接使用即可
1.pox.xml引入依赖
<dependency>
<groupId>com.oopsguy.kaptcha</groupId>
<artifactId>kaptcha-spring-boot-starter</artifactId>
<version>1.0.0-beta-2</version>
</dependency>
2.application.yml加载配置
kaptcha:
items:
# home captcha
home:
path: /home/captcha
session:
key: HOME_KAPTCHA_SESSION_KEY
date: HOME_KAPTCHA_SESSION_DATE
3.运行
输入网址
http://127.0.0.1:8091/home/captcha
8091是我的端口号,你的是多少就替换为多少
进来后就可以看到一个验证码
4.插入前端之中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>验证码</title>
<style>
#inputCaptcha {
height: 30px;
vertical-align: middle;
}
#verificationCodeImg{
vertical-align: middle;
}
#checkCaptcha{
height: 40px;
width: 100px;
}
</style>
</head>
<body>
<h1>输入验证码</h1>
<div id="confirm">
<input type="text" name="inputCaptcha" id="inputCaptcha">
<img id="verificationCodeImg" src="/home/captcha" style="cursor: pointer;" title="看不清?换一张" />
<input type="button" value="提交" id="checkCaptcha">
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$("#verificationCodeImg").click(function(){
$(this).hide().attr('src', '/admin/captcha?dt=' + new Date().getTime()).fadeIn();
});
$("#checkCaptcha").click(function () {
alert("验证码校验");
});
$("#checkCaptcha").click(function () {
$.ajax({
url: "/check",
type: "post",
data: { captcha: $("#inputCaptcha").val() },
success: function (result) {
if (result) {
location.href = "success.html";
} else {
alert("验证码错误");
$("#inputCaptcha").val("");
}
}
});
});
</script>
</body>
</html>
是这个样式
再来一个验证网页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>验证成功页</title>
</head>
<body>
<h1>验证成功</h1>
</body>
</html>
5.后端接收
@RestController
public class CaptchaController {
private static final String CAPTCHA_SESSION_KEY="HOME_KAPTCHA_SESSION_KEY";
private static final String HOME_KAPTCHA_SESSION_DATE="HOME_KAPTCHA_SESSION_DATE";
private static final Long SESSION_TIME_OUT= 60*1000L;
//成功返回true,失败返回false
@RequestMapping("/check")
public Boolean check(String captcha, HttpSession session){
if(captcha==null)return false;
String saveCaptcha = (String)session.getAttribute(CAPTCHA_SESSION_KEY);
Date saveDate = (Date) session.getAttribute(HOME_KAPTCHA_SESSION_DATE);
if(captcha.equals(saveCaptcha)){
if(saveDate==null||System.currentTimeMillis()-saveDate.getTime()<=SESSION_TIME_OUT){
System.out.println("true");
return true;
}
System.out.println("f");
return false;
}
else {
System.out.println("f");
return false;
}
}
}