基础:maven_SSM项目如何实现验证码功能_超*的博客-CSDN博客
先去看基础文章,导入的依赖一样
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha kaptcha() {
DefaultKaptcha kaptcha = new DefaultKaptcha();
// 设置验证码生成器的属性
// 可以根据需要进行配置,例如边框、字符长度、字体颜色、图片大小等
Properties properties = new Properties();
properties.setProperty("kaptcha.border", "no");
properties.setProperty("kaptcha.textproducer.char.length", "4");
properties.setProperty("kaptcha.textproducer.font.color", "black");
properties.setProperty("kaptcha.textproducer.font.size", "30");
properties.setProperty("kaptcha.image.width", "200");
properties.setProperty("kaptcha.image.height", "55");
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}
@RestController
@CrossOrigin
@RequestMapping("/api")
public class CaptchaController {
private final DefaultKaptcha kaptcha;
public CaptchaController(DefaultKaptcha kaptcha) {
this.kaptcha = kaptcha;
}
@Operation(summary = "发送图片验证码")
@GetMapping("/captcha")
public void generateCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
// 生成验证码
String captchaText = kaptcha.createText();
// 将验证码存储到会话中,以便后续验证
HttpSession session = request.getSession();
session.setAttribute("captcha", captchaText);
request.getServletContext();
// 将验证码图片输出到响应中
response.setContentType("image/jpeg");
try (OutputStream outputStream = response.getOutputStream()) {
BufferedImage captchaImage = kaptcha.createImage(captchaText);
ImageIO.write(captchaImage, "jpg", outputStream);
outputStream.flush();
}
}
<el-image src="/app/api/captcha" fit="contain"></el-image>
这里src里写完整请求路径, 我这里/app是进行代理了的。