EasyCaptcha是一个基于Java开发的图形验证码工具,项目地址为: https://github.com/pig-mesh/easy-captcha
1. 引入依赖
<dependency>
<groupId>com.pig4cloud.plugin</groupId>
<artifactId>captcha-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
使用教程在项目地址中已经有了,这里直接贴出demo代码。
后端
@RestController
@RequestMapping("/captcha")
@CrossOrigin
public class CaptchaController {
private RedisUtils redisUtils;
@GetMapping("/get")
public ResultVO getCaptcha() {
// 新建一个算数验证码,并且指定了宽和高(验证码图片的尺寸)
Captcha captcha = new ArithmeticCaptcha(111, 36);
// 设置算数验证的长度。2表示2位数运算
captcha.setLen(2);
// 验证码的结果值
String captchaValue = captcha.text();
// 验证码的图片url
String codeUrl = captcha.toBase64();
// 将结果封装到map中返回给前端
HashMap<String, String> map = new HashMap<>();
map.put("captchaValue", captchaValue);
map.put("codeUrl", codeUrl);
return new ResultVO(10000, map);
}
}
一般来说验证码为保证时效性,是要存储进redis的,这里为了测试方便,没有存进redis,直接返回给前端了。
前端
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>easy-captcha测试</title>
<script type="application/javascript" src="js/axios.min.js"></script>
<script type="application/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="app">
<div>
<img :src="captchaImgSrc" @click="changeCaptcha" height="36px" width="111px" border="1px;" /><br />
<input type="text" v-model="inputValue" /><button type="button" @click="pressOk">确认</button>
</div>
</div>
<script type="application/javascript">
var vm = new Vue({
el: "#app",
data: {
captchaImgSrc: "",
captchaValue: "",
inputValue: ""
},
// 钩子函数,在页面加载,data初始化之后执行,向后端发送请求,获取验证码信息
created() {
axios.get("http://localhost:8080/captcha/get").then(res => {
var vo = res.data;
vm.captchaImgSrc = vo.data.codeUrl;
vm.captchaValue = vo.data.captchaValue;
});
},
methods: {
// 提交验证码后判断对错
pressOk: function() {
if (this.captchaValue === this.inputValue) {
alert("验证码输入正确!");
} else {
alert("验证码输入错误!");
}
},
// 点击验证码刷新
changeCaptcha: function() {
axios.get("http://localhost:8080/captcha/get").then(res => {
var vo = res.data;
vm.captchaImgSrc = vo.data.codeUrl;
vm.captchaValue = vo.data.captchaValue;
});
}
}
})
</script>
</body>
</html>