SpringBoot实现简单的登录验证码

参考了一些资料,完成了这个验证码的功能,下面记录一下功能的实现过程。

一、效果图

二、实现原理

后台生成验证码图片,将图片传到前台。
后台在session中保存验证码内容。
前台输入验证码后传到后台在后台取出session中保存的验证码进行校验。

三、代码

1、建一个config

我是建了一个名叫KaptchaConfig的config

代码如下:

这里配置了验证码的背景加不加边框,和字体颜色,并生成验证码

复制代码
package com.example.demo.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class KaptchaConfig {
    @Value("${kaptcha.border}")
    private String border;

    @Value("${kaptcha.textproducer.font.color}")
    private String fontColor;

    // 其他配置项

    @Bean
    public DefaultKaptcha captchaProducer() {
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", border);
        properties.setProperty("kaptcha.textproducer.font.color", fontColor);
        // 配置其他属性

        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }
}

上面的@value(${})这里面的数据,我是在application.yml里面配置的

复制代码
kaptcha:
  border: "no"
  textproducer:
    font:
      color: pink

2、把验证码返回给前端

首先在controller里面导入两个类

复制代码
@Autowired
    private DefaultKaptcha captchaProducer;

    @Autowired
    private HttpServletRequest request;

其次在controller里面把验证码转换为Base64编码返回给前端

这一步已经把生成的验证码文本存储在session中了

复制代码
@GetMapping("/captcha")
    public void captcha(HttpServletResponse response) throws IOException {
        // 生成验证码文本
        String captchaText = captchaProducer.createText();

        // 将验证码文本存储在Session中
        HttpSession session = request.getSession();
        session.setAttribute("captcha", captchaText);

        // 生成验证码图片
        BufferedImage captchaImage = captchaProducer.createImage(captchaText);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "jpg", baos);
        byte[] captchaBytes = baos.toByteArray();

// 将字节数组转换为Base64编码
        String base64Captcha = Base64.getEncoder().encodeToString(captchaBytes);

// 返回响应
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(base64Captcha);
        writer.flush();
    }

前端接收这个Base64编码需要转换一下

复制代码
const yzm = async () => {
  let ff = await yzmAPI();
  // 解码图片数据
  const decodedData = atob(ff.toString());

// 创建一个Uint8Array来存储解码后的二进制数据
  const arrayBuffer = new Uint8Array(decodedData.length);
  for (let i = 0; i < decodedData.length; i++) {
    arrayBuffer[i] = decodedData.charCodeAt(i);
  }

// 创建一个Blob对象
  const blob = new Blob([arrayBuffer], { type: 'image/jpeg' });

// 创建一个URL对象
  const imageUrl = URL.createObjectURL(blob);
  imgs.value = imageUrl;
}

最后在登录里面判断这个前端传过来的验证码和存起来的验证码对比一下就可以了

复制代码
 HttpSession session = request.getSession();
        String captcha = (String) session.getAttribute("captcha");
        if (!captcha.toString().equals(inputCaptcha.toString())) {
           //写自己的处理方式
        }

以上就完成了验证码登录

相关推荐
重生之我是Java开发战士33 分钟前
【Spring Cloud】认识微服务与工程搭建
spring·spring cloud·微服务
霸道流氓气质37 分钟前
Spring AI 多模态开发指南:图片理解与语音合成
java·人工智能·spring
en.en..41 分钟前
Linux mmap 内存映射深度解析:基于帧缓冲 /dev/fb0
java·服务器·前端
洋不写bug44 分钟前
链表补充练习,双链表的模拟实现
java·数据结构·链表·双链表·底层实现
后台模板学习1 小时前
用 IM 即时聊天项目一次讲清消息去重算法的踩坑与解决方案
java·数据库·spring
秋名RG1 小时前
2026/6/15 系统故障复盘与整改方案
java·架构
今天要早睡_1 小时前
C++ 核心语法速过:命名空间、引用、函数重载与 nullptr 深度解析
android·java·c++
南讯股份Nascent1 小时前
2026年CRM技术选型观察:当“数据打通“成为第一需求,电商CRM的架构价值在哪里
java·大数据·用户运营
心易行者1 小时前
Python自动化测试7步落地法:用python在线运行省掉90%环境配置时间
java·开发语言·人工智能·python·log4j·ai编程
霸道流氓气质2 小时前
Spring AI 技术细节:VectorStore 多库统一抽象
java·人工智能·spring