【springboot系列】springboot整合easy-captcha实现图片验证码

大家好,我是walker
一个从文科自学转行的程序员~
爱好编程,偶尔写写编程文章和生活
欢迎关注公众号【I am Walker】,回复“电子书”,就可以获得200多本编程相关电子书哈~
我的gitee:https://gitee.com/shen-chuhao/walker.git 里面很多技术案例!

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

    <dependency>
        <groupId>com.github.whvcse</groupId>
        <artifactId>easy-captcha</artifactId>
        <version>1.6.2</version>
    </dependency>

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<Object> 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<String, Object> imgResult = new HashMap<String, Object>(2) {{
        put("img", captcha.toBase64());
        put("uuid", uuid);
    }};
    return ResponseEntity.ok(imgResult);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WalkerShen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值