参考了一些资料,完成了这个验证码的功能,下面记录一下功能的实现过程。
一、效果图
二、实现原理
后台生成验证码图片,将图片传到前台。
后台在session中保存验证码内容。
前台输入验证码后传到后台在后台取出session中保存的验证码进行校验。
三、代码
3.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
3.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())) { //写自己的处理方式 }
以上就完成了验证码登录

