1.先安装pom依赖
<!-- 验证码依赖-->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
2.在config目录下新建一个Captcha.java
@Configuration
public class CaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha(){
//验证码生成器
DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
//配置
Properties properties=new Properties();
//是否有边框
properties.setProperty("kaptcha.border","yes");
//设置边框颜色
properties.setProperty("kaptcha.border.color","105,179,90");
//设置验证码
properties.setProperty("kaptcha.session.key","code");
//验证码文本字符颜色和样式
properties.setProperty("kaptcha.textproducer.font.color","blue");
//设置字体样式
properties.setProperty("kaptcha.textproducer.font.names","宋体,楷体,微软雅黑");
//字体大小
properties.setProperty("kaptcha.textproducer.font.size","30");
//验证码文字字符内容范围默认是abced2345678gfynmnpwx
//字符长度默认为5
properties.setProperty("kaptcha.textproducer.char.length","4");
//验证码图片宽度默认200
properties.setProperty("kaptcha.image.width","100");
//验证码图片高度默认40
properties.setProperty("kaptcha.image.height","40");
Config config=new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
3.在Controller目录下新建一个CaptchaController.java
@RestController
public class CaptchaController {
@Autowired
private DefaultKaptcha defaultKaptcha;
@ApiOperation(value="验证码")
@GetMapping(value = "/captcha",produces = "image/jpeg")
public void captcha(HttpServletRequest request, HttpServletResponse response){
//定义response输出类型为image/jpeg类型
response.setDateHeader("Expires",0);
response.addHeader("Cache-Control","post-check=0,pre-check=0");
response.setHeader("Pragma","no-cache");
response.setContentType("image/jpeg");
//生成验证码begin
//获取文本内容
String text=defaultKaptcha.createText();
System.out.println("验证码内容: " + text);
//将验证码放入session
request.getSession().setAttribute("captcha",text);
//根据文本内容创建图形验证码
BufferedImage image=defaultKaptcha.createImage(text);
ServletOutputStream outputStream=null;
try {
outputStream = response.getOutputStream();
//输出流输出图片格式,jpg
ImageIO.write(image,"jpg",outputStream);
outputStream.flush();
}catch (IOException e){
e.printStackTrace();
}finally {
if (null!=outputStream){
try{
outputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
//生成验证码
}
}
4.运行项目,访问localhost:8088/captcha
即可访问成功!