依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
配置KaptchaConfig
@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", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYAZ");
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;
}
}
获取验证码
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
@Autowired
private Producer producer;
@GetMapping("/kaptcha")
public void getKaptcha(HttpServletResponse response, HttpSession session) {
String text = producer.createText();
BufferedImage image = producer.createImage(text);
// 存储到session
session.setAttribute("kaptcha", text);
response.setContentType("image/png");
try {
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(image, "png", outputStream);
} catch (IOException e) {
logger.error("创建验证码失败" + e.getMessage());
}
}