内容简介
上文我们已经整合好了jwt,本文我们开始实现图形验证码接口的实现。
前置条件
本文衔接上文,请从上文开始
spring boot3登录开发(整合jwt)_springboot3 jwt-CSDN博客
图形验证码接口实现
1、导入工具依赖
pom.xml:
<dependency>  <groupId>com.github.penggle</groupId>  <artifactId>kaptcha</artifactId>  <version>最新版本</version>  
</dependency>注意:请替换最新版本为实际可用的最新版本号。
2、配置Kaptcha:
创建一个配置类来配置Kaptcha。这通常包括设置验证码的文本长度、字体、颜色、图片大小等属性,在Spring Boot的配置类中添加Kaptcha的配置。
import com.google.code.kaptcha.impl.DefaultKaptcha;  
import com.google.code.kaptcha.util.Config;  
import java.util.Properties;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  @Configuration  
public class KaptchaConfig {  @Bean  public DefaultKaptcha getDefaultKaptcha() {  DefaultKaptcha defaultKaptcha = new DefaultKaptcha();  Properties properties = new Properties();  // 设置验证码的长度  properties.setProperty("kaptcha.textproducer.char.length", "4");  // 设置字体  properties.setProperty("kaptcha.textproducer.font.names", "宋体");  // 字体大小  properties.setProperty("kaptcha.textproducer.font.size", "30");  // 字体颜色  properties.setProperty("kaptcha.textproducer.font.color", "black");  // 设置图片宽度  properties.setProperty("kaptcha.image.width", "125");  // 设置图片高度  properties.setProperty("kaptcha.image.height", "45");  // 设置背景色  properties.setProperty("kaptcha.background.clear.to.white", "true");  // 设置是否有边框  properties.setProperty("kaptcha.border", "yes");  // 边框颜色  properties.setProperty("kaptcha.border.color", "105,179,90");  // 验证码图片样式  Config config = new Config(properties);  defaultKaptcha.setConfig(config);  return defaultKaptcha;  }  
}3、 创建验证码生成服务
这里用到了redis,需要整合好:Spring Boot与Redis深度整合:实战指南
import com.google.code.kaptcha.impl.DefaultKaptcha;  
import com.google.code.kaptcha.util.Config;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.data.redis.core.StringRedisTemplate;  
import org.springframework.stereotype.Service;  import javax.imageio.ImageIO;  
import javax.servlet.ServletOutputStream;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import java.awt.image.BufferedImage;  
import java.io.ByteArrayOutputStream;  
import java.util.Properties;  @Service  
public class CaptchaService {  private DefaultKaptcha defaultKaptcha;  @Autowired  private StringRedisTemplate redisTemplate;  public CaptchaService() {  defaultKaptcha = new DefaultKaptcha();  Properties properties = new Properties();  // 设置验证码相关属性,如字体、大小、颜色等  properties.setProperty("kaptcha.border", "yes");  properties.setProperty("kaptcha.border.color", "105,179,90");  // ... 其他属性设置  Config config = new Config(properties);  defaultKaptcha.setConfig(config);  }  public void createCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {  String captchaText = defaultKaptcha.createText();  String key = UUID.randomUUID().toString(); // 生成唯一的key  redisTemplate.opsForValue().set(key, captchaText, 60, TimeUnit.SECONDS); // 将验证码保存到Redis,并设置过期时间  request.getSession().setAttribute("captchaKey", key); // 将key保存到session中,用于前端验证  BufferedImage image = defaultKaptcha.createImage(captchaText);  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  ImageIO.write(image, "jpg", byteArrayOutputStream);  byte[] captchaImage = byteArrayOutputStream.toByteArray();  response.setDateHeader("Expires", 0);  response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  response.addHeader("Cache-Control", "post-check=0, pre-check=0");  response.setHeader("Pragma", "no-cache");  response.setContentType("image/jpeg");  ServletOutputStream out = response.getOutputStream();  out.write(captchaImage);  out.flush();  out.close();  }  
}4.、创建验证码控制器
在控制器中创建一个接口,创建一个控制器来处理验证码的生成请求。该接口通常是一个HTTP GET请求,返回验证码图片。
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RestController;  import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  @RestController  
public class CaptchaController {  @Autowired  private CaptchaService captchaService;  @GetMapping("/captcha")  public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {  captchaService.createCaptcha(request, response);  }  
}5.、前端(Vue)
1. 安装Axios(如果尚未安装)
使用npm或yarn安装Axios,以便进行HTTP请求。
npm install axios --save或者
yarn add axios
2. 在Vue组件中请求验证
<template>  <div>  <img :src="captchaSrc" @click="refreshCaptcha" alt="验证码" />  <input type="text" v-model="captchaInput" placeholder="请输入验证码" />  <button @click="submitForm">提交</button>  </div>  
</template>  <script>  
import axios from 'axios';  export default {  data() {  return {  captchaSrc: '',  captchaInput: '',  };  },  methods: {  refreshCaptcha() {  this.getCaptcha();  },  getCaptcha() {  axios.get('/captcha')  .then(response => {  this.captchaSrc = window.URL.createObjectURL(new Blob([response.data]));  })  .catch(error => {  console.error(error);  });  },  submitForm() {  // 提交表单逻辑,包括验证captchaInput是否正确  // ...  },  },  mounted() {  this.getCaptcha();  },  
};  
</script>