一、pom.xml加载该依赖
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
二、RestFul风格,在这里写一个调用验证码的接口:
@GetMapping(value = "/captcha.jpg")
public void captcha(HttpServletResponse response, HttpServletRequest request) throws Exception {
response.setHeader("Cache-Control", "no-store,no-cache");
response.setContentType("image/jpeg");
/**
* 生成文字验证码
*/
String text = producer.createText();
/**
* 生成图片验证码
*/
BufferedImage image = producer.createImage(text);
/**
* 保存验证码到Session
*/
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,text);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image,"jpg",out);
IOUtils.closeQuietly(out);
}
三、写一个KaptchaConfig配置类
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha produer(){
Properties properties = new Properties();
/**
* 验证码有无边框
*/
properties.put("kapcha.border","no");
/**
* 验证码样式
*/
properties.put("kaptcha.textproducer.font.color","black");
/**
* 表示展示几个数字
*/
properties.put("kaptcha.textproducer.char.space","5");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
四、测试一下
可喜可贺 哈哈哈哈
这里是一个真诚的***青年技术交流QQ群:761374713***,不管你是大学生、社畜、想学习变成的其他人员,欢迎大家加入我们,一起成长,一起进步,真诚的欢迎你,不管是技术,还是人生,还是学习方法。有道无术,术亦可求,有术无道,止于术。