一、效果展示
二、Hutool工具类实现验证码生成
2.1 引入依赖
<!--hutool工具包-->
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.15</version>
</dependency
2.2 简单实现方式
@GetMapping("/createCode")public void createCode(HttpServletResponse response) {// 创建剪切型验证码ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(150, 50, 4, 3);// 设置响应头response.setContentType("image/jpeg");response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");String uuidStr = UUID.randomUUID().toString().replace("-", "");response.setHeader("verifyCodeUuid", uuidStr);//使用redis
// ValueOperations valueOperations = redisTemplate.opsForValue();
// valueOperations.set("uuidCode", shearCaptcha.getCode());
// valueOperations.get("uuidCode");uuidCode = shearCaptcha.getCode();// 将验证码图片转换为Base64编码ByteArrayOutputStream baos = new ByteArrayOutputStream();try {shearCaptcha.write(baos);byte[] imgBytes = baos.toByteArray();String imgBase64 = Base64.getEncoder().encodeToString(imgBytes);// 将Base64编码的图片数据作为响应内容response.getOutputStream().write(imgBase64.getBytes());} catch (IOException e) {throw new RuntimeException(e);} finally {try {baos.close();} catch (IOException e) {// 忽略关闭流的异常}}}