Java图形验证码支持gif、中文、算术等

时间:2022-07-27
本文章向大家介绍Java图形验证码支持gif、中文、算术等,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

点击上方「蓝字」关注我们

图形验证码是最经典,也是最常用的验证方式。今天介绍一个非常不错的类库:Java图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目。

官网:

https://gitee.com/whvse/EasyCaptcha

效果图:

0x01:项目引入easy-captcha

<dependencies>
   <dependency>
      <groupId>com.github.whvcse</groupId>
      <artifactId>easy-captcha</artifactId>
      <version>1.6.2</version>
   </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>

扫码二维码

获取更多精彩

Java乐园

有用!分享+在看☟