2020年12月16日 | Wizzer | 评论 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); } } 1,587 total views, 2 views today