目录
此验证码功能是以SpringBoot框架下基于kaptcha插件来实现的。
1.页面生成验证码
2.输入验证码,点击提交,验证用户输入的验证码是否正确,正确则进行页面跳转
1.生成内容(根据词库)
2.生成干扰项
3.二者组成图片,返回
<dependency>
<groupId>com.oopsguy.kaptcha</groupId>
<artifactId>kaptcha-spring-boot-starter</artifactId>
<version>1.0.0-beta-2</version>
</dependency>
kaptcha:
# 图片大小
image:
width: 100
height: 60
# 字体
text-producer:
font:
size: 28
items:
# home captcha
admin:
path: /admin/captcha
session:
key: HOME_KAPTCHA_SESSION_KEY
data: HOME_KAPTCHA_SESSION_DATE
运行:即可在浏览器访问验证码
<!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="/admin/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 () {
$.ajax({
type:"get",
url:"/admin/check",
data:{
captcha:$("#inputCaptcha").val()
},
success:function(result){
if(result){
location.href="success.html";
}else{
alert("验证码错误");
}
}
});
});
</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>
package com.lele.demo.controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.Date;
@RequestMapping("/admin")
@RestController
public class CaptchaController {
private static final String KAPTCHA_SESSION_KEY= "HOME_KAPTCHA_SESSION_KEY";
private static final String KAPTCHA_SESSION_DATE="HOME_KAPTCHA_SESSION_DATE";
//一分钟60秒,一秒1000毫秒
private static final Long SESSION_TIME_OUT=60*1000L;
// 1.从session中获取生成的验证码
// 2.对比前端的验证码与session中的是否一样
//验证成功返回true 失败返回false
@RequestMapping("/check")
public Boolean check(String captcha ,HttpSession session){
if(!StringUtils.hasLength(captcha)){
return false;
}
//从session中获取验证码
String saveCaptcha=(String) session.getAttribute(KAPTCHA_SESSION_KEY);
Date saveDate=(Date) session.getAttribute(KAPTCHA_SESSION_DATE);
//比对验证码
if(captcha.equals(saveCaptcha)){
//比对日期
if(saveDate==null || System.currentTimeMillis()-saveDate.getTime()<SESSION_TIME_OUT){
return true;
}
return true;
}
return false;
}
}
测试后端代码
实现结果