pom.xml

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

生成验证码:

public NutMap getCode() {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 40);
        captcha.getArithmeticString();  // 获取运算的公式:3+2=?
        String text = captcha.text();
        redisService.setex(RedisConstant.REDIS_CAPTCHA_KEY + uuid, 180, text);
        return NutMap.NEW().addv("key", uuid).addv("codeUrl", captcha.toBase64());
    }

验证验证码:(表单传递验证码及验证码key)

public void checkCode(String key, String code) throws CaptchaException {
        String codeFromRedis = redisService.get(RedisConstant.REDIS_CAPTCHA_KEY + key);

        if (Strings.isBlank(code)) {
            throw new CaptchaException("请输入验证码");
        }
        if (Strings.isEmpty(codeFromRedis)) {
            throw new CaptchaException("验证码已过期");
        }
        if (!Strings.equalsIgnoreCase(code, codeFromRedis)) {
            throw new CaptchaException("验证码不正确");
        }
        redisService.del(RedisConstant.REDIS_SMSCODE_KEY + key);
    }


try {
      validateService.checkCode(key, code);
} catch (CaptchaException e) {
      return Result.error(e.getMessage());
}

异常类:

public class CaptchaException extends Exception{
    public CaptchaException(String message) {
        super(message);
    }
}

402 total views, 4 views today

发表评论

电子邮件地址不会被公开。 必填项已用*标注