当前位置:   article > 正文

Spring Boot 3登录开发进阶:图形验证码接口的实现

Spring Boot 3登录开发进阶:图形验证码接口的实现

内容简介

上文我们已经整合好了jwt,本文我们开始实现图形验证码接口的实现。

前置条件

本文衔接上文,请从上文开始

spring boot3登录开发(整合jwt)_springboot3 jwt-CSDN博客

图形验证码接口实现

1、导入工具依赖

pom.xml:

  1. <dependency>
  2. <groupId>com.github.penggle</groupId>
  3. <artifactId>kaptcha</artifactId>
  4. <version>最新版本</version>
  5. </dependency>

注意:请替换最新版本为实际可用的最新版本号。

2、配置Kaptcha

创建一个配置类来配置Kaptcha。这通常包括设置验证码的文本长度、字体、颜色、图片大小等属性,在Spring Boot的配置类中添加Kaptcha的配置。

  1. import com.google.code.kaptcha.impl.DefaultKaptcha;
  2. import com.google.code.kaptcha.util.Config;
  3. import java.util.Properties;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. @Configuration
  7. public class KaptchaConfig {
  8. @Bean
  9. public DefaultKaptcha getDefaultKaptcha() {
  10. DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
  11. Properties properties = new Properties();
  12. // 设置验证码的长度
  13. properties.setProperty("kaptcha.textproducer.char.length", "4");
  14. // 设置字体
  15. properties.setProperty("kaptcha.textproducer.font.names", "宋体");
  16. // 字体大小
  17. properties.setProperty("kaptcha.textproducer.font.size", "30");
  18. // 字体颜色
  19. properties.setProperty("kaptcha.textproducer.font.color", "black");
  20. // 设置图片宽度
  21. properties.setProperty("kaptcha.image.width", "125");
  22. // 设置图片高度
  23. properties.setProperty("kaptcha.image.height", "45");
  24. // 设置背景色
  25. properties.setProperty("kaptcha.background.clear.to.white", "true");
  26. // 设置是否有边框
  27. properties.setProperty("kaptcha.border", "yes");
  28. // 边框颜色
  29. properties.setProperty("kaptcha.border.color", "105,179,90");
  30. // 验证码图片样式
  31. Config config = new Config(properties);
  32. defaultKaptcha.setConfig(config);
  33. return defaultKaptcha;
  34. }
  35. }

3、 创建验证码生成服务

这里用到了redis,需要整合好:Spring Boot与Redis深度整合:实战指南

  1. import com.google.code.kaptcha.impl.DefaultKaptcha;
  2. import com.google.code.kaptcha.util.Config;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.data.redis.core.StringRedisTemplate;
  5. import org.springframework.stereotype.Service;
  6. import javax.imageio.ImageIO;
  7. import javax.servlet.ServletOutputStream;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import java.awt.image.BufferedImage;
  11. import java.io.ByteArrayOutputStream;
  12. import java.util.Properties;
  13. @Service
  14. public class CaptchaService {
  15. private DefaultKaptcha defaultKaptcha;
  16. @Autowired
  17. private StringRedisTemplate redisTemplate;
  18. public CaptchaService() {
  19. defaultKaptcha = new DefaultKaptcha();
  20. Properties properties = new Properties();
  21. // 设置验证码相关属性,如字体、大小、颜色等
  22. properties.setProperty("kaptcha.border", "yes");
  23. properties.setProperty("kaptcha.border.color", "105,179,90");
  24. // ... 其他属性设置
  25. Config config = new Config(properties);
  26. defaultKaptcha.setConfig(config);
  27. }
  28. public void createCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
  29. String captchaText = defaultKaptcha.createText();
  30. String key = UUID.randomUUID().toString(); // 生成唯一的key
  31. redisTemplate.opsForValue().set(key, captchaText, 60, TimeUnit.SECONDS); // 将验证码保存到Redis,并设置过期时间
  32. request.getSession().setAttribute("captchaKey", key); // 将key保存到session中,用于前端验证
  33. BufferedImage image = defaultKaptcha.createImage(captchaText);
  34. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  35. ImageIO.write(image, "jpg", byteArrayOutputStream);
  36. byte[] captchaImage = byteArrayOutputStream.toByteArray();
  37. response.setDateHeader("Expires", 0);
  38. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
  39. response.addHeader("Cache-Control", "post-check=0, pre-check=0");
  40. response.setHeader("Pragma", "no-cache");
  41. response.setContentType("image/jpeg");
  42. ServletOutputStream out = response.getOutputStream();
  43. out.write(captchaImage);
  44. out.flush();
  45. out.close();
  46. }
  47. }

4.、创建验证码控制器

在控制器中创建一个接口,创建一个控制器来处理验证码的生成请求。该接口通常是一个HTTP GET请求,返回验证码图片。

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. @RestController
  7. public class CaptchaController {
  8. @Autowired
  9. private CaptchaService captchaService;
  10. @GetMapping("/captcha")
  11. public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
  12. captchaService.createCaptcha(request, response);
  13. }
  14. }

5.、前端(Vue)

1. 安装Axios(如果尚未安装)

使用npm或yarn安装Axios,以便进行HTTP请求。

npm install axios --save

或者

yarn add axios
 2. 在Vue组件中请求验证
  1. <template>
  2. <div>
  3. <img :src="captchaSrc" @click="refreshCaptcha" alt="验证码" />
  4. <input type="text" v-model="captchaInput" placeholder="请输入验证码" />
  5. <button @click="submitForm">提交</button>
  6. </div>
  7. </template>
  8. <script>
  9. import axios from 'axios';
  10. export default {
  11. data() {
  12. return {
  13. captchaSrc: '',
  14. captchaInput: '',
  15. };
  16. },
  17. methods: {
  18. refreshCaptcha() {
  19. this.getCaptcha();
  20. },
  21. getCaptcha() {
  22. axios.get('/captcha')
  23. .then(response => {
  24. this.captchaSrc = window.URL.createObjectURL(new Blob([response.data]));
  25. })
  26. .catch(error => {
  27. console.error(error);
  28. });
  29. },
  30. submitForm() {
  31. // 提交表单逻辑,包括验证captchaInput是否正确
  32. // ...
  33. },
  34. },
  35. mounted() {
  36. this.getCaptcha();
  37. },
  38. };
  39. </script>
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/430747
推荐阅读
相关标签
  

闽ICP备14008679号