1、设置 Maven
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
|
2、设置一个随机字符串(用来存在 Redis 中作为图片的 key)
1 2 3 4 5 6
| @GetMapping("/getToken") public String getToken() { String token = UUID.randomUUID().toString(); return token; }
|
3、生成验证码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| @PostMapping("/getcode") public void getCode(HttpServletResponse response,String token) throws Exception {
Object[] objs = VerifyUtil.newBuilder() .setWidth(100) .setHeight(35) .setSize(4) .setLines(3) .setFontSize(25) .setTilt(false) .setBackgroundColor(Color.LIGHT_GRAY) .build() .createImage(); System.out.println(objs[0]);
redisTemplate.setValueSerializer(new StringRedisSerializer()); redisTemplate.opsForValue().set(("VERIFY_CODE_" + 1), "3", 5 * 60, TimeUnit.SECONDS);
String buyCode = String.valueOf(objs[0]); String buyKey = "buy_" + token;
RedisUtils.set(buyKey, buyCode, 60 * 1 + 5);
BufferedImage image = (BufferedImage) objs[1]; response.setContentType("image/png"); OutputStream os = response.getOutputStream(); ImageIO.write(image, "png", os);
}
|
4、验证验证码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @PostMapping("/checkcode") public JsonResult checkCode(String code, HttpServletRequest request,String token) { JsonResult result = new JsonResult(); String buyKey = "buy_" + token; String codeCheck = RedisUtils.get(buyKey); Long times = RedisUtils.ttl(buyKey); if (times == -2) { result.setSuccess(true); result.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); result.setMsg("验证码过期"); return result; } if (codeCheck.equals(code)) { result.setSuccess(true); result.setCode(HttpStatus.SC_OK); result.setMsg("验证码正确"); return result; } result.setSuccess(true); result.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); result.setMsg("请输入正确的验证码"); return result; }
|
如果需要 Redis工具类可以在下面留言备注邮箱