1.导入依赖
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
2.SpringBoot项目加入配置类
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* 生成验证码配置
*/
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha producer() {
Properties properties = new Properties();
properties.put("kaptcha.border", "no");
properties.put("kaptcha.textproducer.font.color", "black");
properties.put("kaptcha.textproducer.char.space", "5");
properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
3.写一个获取图形验证码的方法(最好在service类写)
/**
* 获取图形验证码
*
*
* @return BufferedImage
*/
public BufferedImage getCaptcha() {
//生成文字验证码
String code = producer.createText();
return producer.createImage(code);
}
4.写一个图形验证码获取接口(Controller层写)
/**
* 图形验证码接口
*
* @param response
* @param uuid
* @throws IOException
*/
@GetMapping("captcha.jpg")
public void captcha(HttpServletResponse response) throws IOException {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
//获取图片验证码 并把图片写入到响应中
BufferedImage image = getCaptcha(uuid);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
IOUtils.closeQuietly(out);
}
5. 特别简单,调用接口就可以看见我们的图标啦
如果你们要做登录把验证码加入缓存然后校验登录的话,自己会的可以用自己的方法做,不会的伙伴可以私信给我或者留言评论哦。