pom.xml

com.github.whvcse

easy-captcha

1.6.2

生成验证码:

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);

}

}

148 total views, 5 views today

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐