1. 导入依赖
- 导入
kaptcha
依赖:
<!-- 验证码生成 -->
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2. 编写配置类:
@Configuration
public class KaptchaConfig {
@Bean
public Producer kaptchaProducer() {Properties properties = new Properties();
properties.setProperty("kaptcha.image.width","100");
properties.setProperty("kaptcha.image.height","40");
properties.setProperty("kaptcha.textproducer.font.size","32");
properties.setProperty("kaptcha.textproducer.font.color","0,0,0");
properties.setProperty("kaptcha.textproducer.char.string","0123456789ABCDEFGHIJKLMOPQRSTUVWXYZ");
properties.setProperty("kaptcha.textproducer.char.length","4"); // 验证码长度
properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
DefaultKaptcha kaptcha = new DefaultKaptcha();
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}
3. 编写 Controller 将验证码存入 session 并以图片的形式传回前端
/**
* 生成验证码并返回
*
* @param response
* @param session
*/
@GetMapping("/kaptcha")
public void getKaptchaImage(HttpServletResponse response, HttpSession session) {
String text = producer.createText();
BufferedImage image = producer.createImage(text);
// 将验证码存到session中
session.setAttribute("kaptcha", text);
// 将图片返回给浏览器
response.setContentType("image/png");
try {
OutputStream os = response.getOutputStream();
// 利用写出图片的工具类
ImageIO.write(image, "png", os);
} catch (IOException e) {
logger.error(e.getMessage());
}
}
网友评论