1. 導入依賴
導入kaptcha依賴:
com.github.penggle
kaptcha
2.3.2
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());
}
}