第一步:导包(maven环境下)
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
第二步:使用DefaultKaptcha类需先对验证码样式进行配置
@Configuration
public class KaptchaConfiguration {
@Bean
public DefaultKaptcha getDefaultKaptcha() {
com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
Properties properties = new Properties();
//--------------------------------------------------------------------------------------
properties.put("kaptcha.textproducer.char.string", "0123456789");
properties.put("kaptcha.border", "no");
properties.put("kaptcha.textproducer.font.color", "black");
properties.put("kaptcha.textproducer.char.length","4");
properties.put("kaptcha.image.height","40");
properties.put("kaptcha.image.width","150");
properties.put("kaptcha.textproducer.font.size","30");
properties.put("kaptcha.session.key", "verifyCode");
properties.put("kaptcha.textproducer.char.space", "5");
properties.setProperty("kaptcha.image.width", "164");
properties.setProperty("kaptcha.image.height", "64");
properties.put("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
//--------------------------------------------------------------------------------------
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
注释内的部分为验证码相关配置,可不设置,默认即可
但是Properties 和 Config 需new ,否则运行报空指针
第三步:生成验证码
@RestController
@RequestMapping("/a")
public class Kaptcha {
@Autowired
private DefaultKaptcha defaultKaptcha;
@RequestMapping("/verifyCode")
public void defaultKaptcha (HttpServletRequest request , HttpServletResponse response) throws IOException {
//生成验证码
String verifyCode = defaultKaptcha.createText();
System.out.println(verifyCode);
//写到session中,后续和前端传来的验证码比对
HttpSession session = request.getSession();
session.setAttribute("verifyCode",verifyCode);
//生成验证码图片流
BufferedImage image = defaultKaptcha.createImage(verifyCode);
//设置响应头
response.setHeader("Cache-Control" , "no-store");
response.setHeader("Pragme" , "no-cache");
response.setDateHeader("Expires",0);
response.setContentType("image/jpeg");
//写到响应输出流中
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(image,"jpg",outputStream);
outputStream.flush();
outputStream.close();
}
}
Properties属性(官网或者百度即可)