Java图形验证码支持gif、中文、算术等
![](https://filescdn.proginn.com/42d07b72a907298277e84d2222d4b21c/8c685504727c097b2295bc1dc8fdcba6.webp)
点击上方「蓝字」关注我们
![](https://filescdn.proginn.com/fbaac128112157facb58bdec02e9731b/f08f7e2a6baf9ca4483a0b5257727d3d.webp)
图形验证码是最经典,也是最常用的验证方式。今天介绍一个非常不错的类库:Java图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目。
官网:
https://gitee.com/whvse/EasyCaptcha
效果图:
0x01:项目引入easy-captcha
<dependencies>
<dependency>
<groupId>com.github.whvcsegroupId>
<artifactId>easy-captchaartifactId>
<version>1.6.2version>
dependency>
dependencies>
0x02:SpringBoot项目创建图形验证码
前后端分离项目中建议不要存储在session中;而使用分布式session,存储在redis中,redis存储需要一个key,key一同返回给前端用于验证输入。
@Controller
public class CaptchaController {
@Autowired
private RedisUtil redisUtil;
@ResponseBody
@RequestMapping("/vcode/captcha")
public JsonResult captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
String verCode = specCaptcha.text().toLowerCase();
String key = UUID.randomUUID().toString();
// 存入redis并设置过期时间为30分钟
redisUtil.setEx(key, verCode, 30, TimeUnit.MINUTES);
// 将key和base64返回给前端
return JsonResult.ok().put("key", key).put("image", specCaptcha.toBase64());
}
@ResponseBody
@PostMapping("/vcode/vaild")
public JsonResult login(String username,String password,String verCode,String verKey){
// 获取redis中的验证码
String redisCode = redisUtil.get(verKey);
// 判断验证码
if (verCode==null || !redisCode.equals(verCode.trim().toLowerCase())) {
return JsonResult.error("验证码不正确");
}
}
}
0x03:前端使用ajax获取验证码并验证
<img id="verImg" width="130px" height="48px"/>
<script>
var verKey;
// 获取验证码
$.get('/vcode/captcha', function(res) {
verKey = res.key;
$('#verImg').attr('src', res.image);
},'json');
// 登录
$.post('/vcode/login', {
verKey: verKey,
verCode: '8u6h',
username: 'admin',
password: 'admin'
}, function(res) {
console.log(res);
}, 'json');
script>
![](https://filescdn.proginn.com/2a731d3de9f0843bba66a5f11eb63b5a/2d11ced8937bdc7f927846b38638a355.webp)
扫码二维码
获取更多精彩
Java乐园
![](https://filescdn.proginn.com/6546634f19ce1c97a3e4b18255d7afdf/d4c5399e63680ef7152b242c56978b28.webp)
评论