基于spring boot应用做的演示,先引入如下起步依赖:
<dependency><groupId>com.baomidou</groupId><artifactId>kaptcha-spring-boot-starter</artifactId><version>1.1.0</version></dependency>
新建kaptcha相关的配置类,如下:
@Configuration
public class KaptchaConfig {@Bean@Qualifier("kaptchaOne")public DefaultKaptcha Kaptcha() {DefaultKaptcha kaptcha = new DefaultKaptcha();Properties properties = new Properties();//设置验证码个数,默认是5properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");//设置字体间隔properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "6");// 验证码文本字符颜色properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black");//干扰实现类properties.setProperty(Constants.KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");//图片样式,目前是水纹,还有鱼眼以及阴影样式properties.setProperty(Constants.KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.WaterRipple");Config config = new Config(properties);kaptcha.setConfig(config);return kaptcha;}
}
以上只是简单的示例配置,kaptcha还支持很多其他的自定义配置项。
写一个接口,调用试试,如下:
@RequestMapping("/test")
@Controller
public class DemoController {@Resourceprivate Producer kaptchaOne;@GetMapping("/getKaptcha")public void getKaptcha(HttpServletRequest request, HttpServletResponse response) {//生成数字,后续可以存到redis,做判断String text = kaptchaOne.createText();System.out.println("验证码是:" + text);BufferedImage bufferedImage = kaptchaOne.createImage(text);try (ServletOutputStream outputStream = response.getOutputStream()) {ImageIO.write(bufferedImage, "jpg", outputStream);outputStream.flush();} catch (IOException e) {System.out.println("获取验证码失败:" + e.getMessage());}}
}
浏览器访问http://localhost:8082/test/getKaptcha,结果如下: