当前位置:   article > 正文

Spring Boot引入第三方工具EasyCaptcha生成图形验证码(包含中文验证码和算数验证码)_springboot easy-captcha

springboot easy-captcha

目录

1.简介

2.maven方式引入 

3.后端代码

4.前端使用ajax获取验证码:

6.验证码效果


1.简介

 EasyCaptcha,Java图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目。

2.maven方式引入 

  1. <!-- 验证码 -->
  2. <dependencies>
  3. <dependency>
  4. <groupId>com.github.whvcse</groupId>
  5. <artifactId>easy-captcha</artifactId>
  6. <version>1.6.2</version>
  7. </dependency>
  8. </dependencies>

3.后端代码

前后端分离项目建议不要存储在session中,存储在redis中,redis存储需要一个key,key一同返回给前端用于验证输入

  1. @Controller
  2. public class CaptchaController {
  3. @Autowired
  4. private RedisUtil redisUtil;
  5. @ResponseBody
  6. @RequestMapping("/captcha")
  7. public JsonResult captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
  8. //动态验证码
  9. GifCaptcha gifCaptcha = new GifCaptcha(130,48,4);
  10. //静态验证码
  11. SpecCaptcha specCaptcha = new SpecCaptcha(130,48,4);
  12. //中文验证码
  13. ChineseCaptcha chineseCaptchaAbstract = new ChineseCaptcha(130,28,4);
  14. //算术验证码
  15. ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(130 , 28 , 4);
  16. String verCode = specCaptcha.text().toLowerCase();
  17. String key = UUID.randomUUID().toString();
  18. // 存入redis并设置过期时间为30分钟
  19. redisUtil.setEx(key, verCode, 30, TimeUnit.MINUTES);
  20. //key和base64返回给前端
  21. return JsonResult.ok().put("key", key).put("image", specCaptcha.toBase64());
  22. }
  23. @ResponseBody
  24. @PostMapping("/login")
  25. public JsonResult login(String username,String password,String verCode,String verKey){
  26. // 获取redis中的验证码
  27. String redisCode = redisUtil.get(verKey);
  28. // 判断验证码
  29. if (verCode==null || !redisCode.equals(verCode.trim().toLowerCase())) {
  30. return JsonResult.error("验证码不正确");
  31. }
  32. }
  33. }

4.前端使用ajax获取验证码:

  1. <img id="verImg" width="130px" height="48px"/>
  2. <script>
  3. var verKey;
  4. // 获取验证码
  5. $.get('/captcha', function(res) {
  6. verKey = res.key;
  7. $('#verImg').attr('src', res.image);
  8. },'json');
  9. // 登录
  10. $.post('/login', {
  11. verKey: verKey,
  12. verCode: '8u6h',
  13. username: 'admin'
  14. password: 'admin'
  15. }, function(res) {
  16. console.log(res);
  17. }, 'json');
  18. </script>

6.验证码效果

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/46517?site
推荐阅读
相关标签
  

闽ICP备14008679号