0.引入依赖:
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
1.添加配置类(SpringBoot)
@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.char.length", "4");
properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
properties.put("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.FishEyeGimpy");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
1.1.配置项说明列表
项目 | 说明 | 默认值 |
---|
kaptcha.border | 是否有边框 | yes,可选:yes,no |
kaptcha.border.color | 边框颜色 | Color.BLACK |
kaptcha.border.thickness | 边框厚度 | 1 |
kaptcha.producer.impl | 默认 | DefaultKaptcha,可自己实现Producer接口 |
kaptcha.textproducer.impl | 文本生成器 | DefaultTextCreator,可自己实现TextProducer接口 |
kaptcha.textproducer.char.string | 文本生成器可使用的字符 | abcde2345678gfynmnpwx |
kaptcha.textproducer.char.length | 生成文本字符长度 | 5 |
kaptcha.textproducer.font.names | 生成文本的字体名称 | Arial |
kaptcha.textproducer.font.size | 生成文本的字号 | 40 |
kaptcha.textproducer.font.color | 生成文本的颜色 | Color.BLACK |
kaptcha.textproducer.char.space | 生成文本的间隔的空格数 | 2 |
kaptcha.noise.impl | 干扰器实现类 | DefaultNoise,可自己实现NoiseProducer接口 |
kaptcha.noise.color | 生成干扰元素的颜色 | Color.BLACK |
kaptcha.obscurificator.impl | 遮挡实现类 | WaterRipple,可自己实现GimpyEngine接口 |
kaptcha.word.impl | 文字呈现渲染器实现类 | DefaultWordRenderer,可自己实现WordRenderer接口 |
kaptcha.background.impl | 背景 | DefaultBackground,可自己实现BackgroundProducer接口 |
kaptcha.background.clear.from | 渐变背景颜色开始值 | Color.LIGHT_GRAY |
kaptcha.background.clear.to | 渐变背景颜色结束值 | Color.WHITE |
kaptcha.image.width | 图片宽度 | 200 |
kaptcha.image.height | 图片高度 | 50 |
kaptcha.session.key | 获取Session中验证码的Key | KAPTCHA_SESSION_KEY |
kaptcha.session.date | 获取Session时间的Key | KAPTCHA_SESSION_DATE |
2 验证码控制器
@Controller
public class KaptchaController {
@Resource
private Producer producer;
@GetMapping("captcha.jpg")
public void captcha(HttpServletResponse response) throws IOException {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
String code = producer.createText();
BufferedImage image = producer.createImage(code);
ShiroUtils.setSessionAttribute("KAPTCHA_SESSION_KEY", code);
String kaptcha = ShiroUtils.getKaptcha("KAPTCHA_SESSION_KEY");
log.debug("session中的当前验证码:{}", kaptcha);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
}
}