Java后端如何生成验证码?

2022-05-09 13:32:15 浏览数 (1)

1.判断配置中是否开启验证码功能 2.生成验证码uuid,verifyKey,验证码答案和验证码图片 3.将verifyKey和答案存入redis 4.将uuid和图片返回

代码语言:javascript复制
 1    /**
 2      * 生成验证码
 3      */
 4     @GetMapping("/captchaImage")
 5     public AjaxResult getCode(HttpServletResponse response) throws IOException
 6     {
 7         AjaxResult ajax = AjaxResult.success();
 8         boolean captchaOnOff = configService.selectCaptchaOnOff();
 9         ajax.put("captchaOnOff", captchaOnOff);
10         if (!captchaOnOff)
11         {
12             return ajax;
13         }
14 
15         // 保存验证码信息
16         String uuid = IdUtils.simpleUUID();
17         String verifyKey = Constants.CAPTCHA_CODE_KEY   uuid;
18 
19         String capStr = null, code = null;
20         BufferedImage image = null;
21 
22         // 生成验证码
23         String captchaType = RuoYiConfig.getCaptchaType();
24         if ("math".equals(captchaType))
25         {
26             String capText = captchaProducerMath.createText();
27             capStr = capText.substring(0, capText.lastIndexOf("@"));
28             code = capText.substring(capText.lastIndexOf("@")   1);
29             image = captchaProducerMath.createImage(capStr);
30         }
31         else if ("char".equals(captchaType))
32         {
33             capStr = code = captchaProducer.createText();
34             image = captchaProducer.createImage(capStr);
35         }
36 
37         redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
38         // 转换流信息写出
39         FastByteArrayOutputStream os = new FastByteArrayOutputStream();
40         try
41         {
42             ImageIO.write(image, "jpg", os);
43         }
44         catch (IOException e)
45         {
46             return AjaxResult.error(e.getMessage());
47         }
48 
49         ajax.put("uuid", uuid);
50         ajax.put("img", Base64.encode(os.toByteArray()));
51         return ajax;
52     }

0 人点赞