1.从Mvn中复制kaptcha的Mavenhttps://mvnrepository.com/artifact/com.github.penggle/kaptcha/2.3.2
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2.在项目中的pom.xml中粘贴,导入jar包
3.自定义一个配置类KaptchaConfig,中定义一个方法,配置类上面加上配置注解@Configuration,方法中加上@ Bean注解,交给Spring容器管理
4.在方法中创建Properties对象,在Properties对象中设置验证码的格式
Properties properties = new Properties();
properties.setProperty("kaptcha.image.width", "100");//设置验证码图片的宽度
properties.setProperty("kaptcha.image.height", "40");//设置验证码图片的高度
properties.setProperty("kaptcha.textproducer.font.size", "32");//设置验证码的字体大小
properties.setProperty("kaptcha.textproducer.font.color", "0,0,0");//设置验证码字体颜色
properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYAZ");//设置验证码的字符范围在全体数字和大写字母中选取
properties.setProperty("kaptcha.textproducer.char.length", "4");//设置验证码的长度
properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");//设置验证码无噪点,无干扰线
5.创建Producer的实现对象DefaultKaptcha
DefaultKaptcha kaptcha=new DefaultKaptcha()
6.创建配置对象Config,构造方法中传入Properties对象
Config config=new Config(Proerties)
7.调用DefaultKaptcha 对象中的方法setConfig(),将配置对象Config传入
kaptcha.setConfig(config);
8.返回kaptcha对象
package com.nowcoder.community.config;
import com.google.code.kaptcha.Producer;
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 Producer kaptchaProducer() {
Properties properties = new Properties();
properties.setProperty("kaptcha.image.width", "100");
properties.setProperty("kaptcha.image.height", "40");
properties.setProperty("kaptcha.textproducer.font.size", "32");
properties.setProperty("kaptcha.textproducer.font.color", "0,0,0");
properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYAZ");
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;
}
}
9.在Controller控制器定义的类中,定义一个方法,用来生成验证码
@Autowired
private Producer kaptchaProducer;
@RequestMapping(path = "/kaptcha",method = RequestMethod.GET)
public void getKaptcha(HttpServletResponse response, HttpSession session){
//生成验证码
String text = kaptchaProducer.createText();
BufferedImage image = kaptchaProducer.createImage(text);
//将验证码存入Session
session.setAttribute("kaptcha",text);
//将图片输出给浏览器
response.setContentType("image/png");
try {
OutputStream os = response.getOutputStream();
//用工具输出
ImageIO.write(image,"png",os);
} catch (IOException e) {
logger.error("响应验证码失败",e.getMessage());
}
}