栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot整合easy-captcha实现图片验证码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot整合easy-captcha实现图片验证码

easy-captcha 图片验证码
使用
1、导入依赖
在maven仓库中查找,发现只有这个依赖,所以直接复制这个即可

    
        com.github.whvcse
        easy-captcha
        1.6.2
    

2、使用
总共有这么多种验证类型

3、测试
public static void main(String[] args) {

    
    ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(138, 48);
    //定义几位数的运算,默认是2位数
    arithmeticCaptcha.setLen(3);
    //获取算数式
    String arithmeticString = arithmeticCaptcha.getArithmeticString();
    //获取返回结果
    String result = arithmeticCaptcha.text();
    //返回图片格式
    String imageUrl = arithmeticCaptcha.tobase64();
    System.out.println("arithmeticString:"+arithmeticString);
    System.out.println("text:"+result);
    System.out.println("图片:"+imageUrl);

    
    ChineseCaptcha chineseCaptcha = new ChineseCaptcha();
    String chineseRes = chineseCaptcha.text();
    String chineseUrl = chineseCaptcha.tobase64();
    System.out.println("chineseRes:"+chineseRes);
    System.out.println("chineseUrl:"+chineseUrl);
}

返回结果:
//算数验证码返回结果
arithmeticString:3x6+5=?
text:23
图片:data:image/png;base64 …

//中文返回结果
chineseRes:个动来紧
chineseUrl:data:image/png;base64 …

4、最佳实践
可以结合redis,使用uuid作为key,结果作为value存储起来

@GetMapping(value = "/code")
public ResponseEntity getCode() {
    // 算术类型 
    ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
    // 几位数运算,默认是两位
    captcha.setLen(2);
    // 获取运算的结果
    String result = "";
    try {
        result = new Double(Double.parseDouble(captcha.text())).intValue() + "";
    } catch (Exception e) {
        result = captcha.text();
    }
    //生成uuid,用于判断
    String uuid = properties.getCodeKey() + IdUtil.simpleUUID();

	// 将结果和过期时间存起来,并设置过期时间
    redisUtils.set(uuid, result, expiration, TimeUnit.MINUTES);
    // 使用map或者对象存储验证码信息,并返回给前端
    Map imgResult = new HashMap(2) {{
        put("img", captcha.tobase64());
        put("uuid", uuid);
    }};
    return ResponseEntity.ok(imgResult);
}


转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号