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())) {
           //写自己的处理方式
        }

以上就完成了验证码登录

相关推荐
CoderYanger1 天前
C.滑动窗口-求子数组个数-越长越合法——2799. 统计完全子数组的数目
java·c语言·开发语言·数据结构·算法·leetcode·职场和发展
C++业余爱好者1 天前
Java 提供了8种基本数据类型及封装类型介绍
java·开发语言·python
想用offer打牌1 天前
RocketMQ如何防止消息丢失?
java·后端·架构·开源·rocketmq
皮卡龙1 天前
Java常用的JSON
java·开发语言·spring boot·json
利刃大大1 天前
【JavaSE】十三、枚举类Enum && Lambda表达式 && 列表排序常见写法
java·开发语言·枚举·lambda·排序
float_六七1 天前
Java反射:万能遥控器拆解编程
java·开发语言
han_hanker1 天前
java 异常类——详解
java·开发语言
源码获取_wx:Fegn08951 天前
基于springboot + vue健身房管理系统
java·开发语言·前端·vue.js·spring boot·后端·spring
峥嵘life1 天前
Android16 EDLA 认证测试CTS问题分析解决
android·java·服务器
Mr1ght1 天前
为什么 InheritableThreadLocal 在 Spring 线程池中“偶尔”能传递变量?——一次线程池上下文传播的误解
java·spring