1.导入jar包Kaptcha
添加进pom.xml文件里
2.
@Configuration
//这个注解表示这不是一个普通类,是一个配置类
public class KaptchaConfig
{
@Bean
//通过bean注解,声明一个bean,这个bean将会被spring容器所管理,装配
public static Producer kaptchaProducer()//Product是接口类型,后面是bean的名字
{
Properties properties = new Properties();
properties.setProperty("kaptcha.image.width", "100");//图片宽度
properties.setProperty("kaptcha.image.height", "100");//图片高度
properties.setProperty("kaptcha.textproducer.font.size", "40");//字号大小
properties.setProperty("kaptcha.textproducer.font.color", "0,0,0");//字体颜色黑色
properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");//生成随机字符,范围是后买你的数字+字母
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;
}
}
3.
//生成验证码:
String text=kaptchaProducer.createText();
BufferedImage image= kaptchaProducer.createImage(text);
最后效果: