- 引入依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
- kaptcha配置类
@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","black");
properties.setProperty("kaptcha.textproducer.char.string","0123456789QWERTYUIOPASSDFGHJKLZXCVBNM");//文本集合
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;
}
}
- 生成验证码
@Autowired
private Producer kaptchaProduce;
@RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
public void getKaptcha(HttpServletResponse response, HttpSession session){ //返回给浏览器的是图片,不是html,需要用response
//生成验证码
String text = kaptchaProduce.createText();
BufferedImage image = kaptchaProduce.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());
}
}
之后前端直接调用这个方法就可以出现验证码了,不过最好将验证码存到redis中而不是session中,给验证码设置归属人和失效时间