导入库
在Maven仓库搜索kaptcha,将下面的内容拷贝到pom.xml中:
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
封装配置类
新建KaptchaConfig.java类,
@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", "0123456789abcdefghijklmnopqrstuvwxyz"); // 验证码可选的字符
properties.setProperty("kaptcha.textproducer.char.length", "4"); //验证码长度
properties.setProperty("kaptcha.textproducer.char.impl",
"com.google.code.kaptcha.impl.NoNoise"); // 验证码图片中加什么干扰
DefaultKaptcha kaptcha = new DefaultKaptcha();
Config config = new Config();
kaptcha.setConfig(config);
return kaptcha;
}
}
在其他类中调用
@Autowired // 注入
private Producer kaptchaProducer;
@RequestMapping(path = "/kaptcha", method = RequestMethod.GET) // 请求
public void getKaptcha(HttpServletResponse response, HttpSession session){
// 生成验证码
String text = kaptchaProducer.createText();
BufferedImage image = kaptchaProducer.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("verification code request failed : " + e.getMessage());
}
}