SpringBoot 图片验证码kaptcha框架的集成
一、添加依赖
<!-- 图片验证码 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
二、编写配置文件
@Configuration
public class KaptchaConfig {
/**
* 验证码配置
* @return
*/
@Bean
public DefaultKaptcha getDefaultKaptcha(){
DefaultKaptcha defaultKaptcha=new DefaultKaptcha();
Properties properties=new Properties();
//是否有边框
properties.setProperty(Constants.KAPTCHA_BORDER,"yes");
//验证码文本颜色
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR,"red");
//验证码图片宽度
properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH,"180");
//验证码图片高度
properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT,"80");
//文本字符大小
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE,"39");
//验证码session的值
properties.setProperty(Constants.KAPTCHA_SESSION_CONFIG_KEY,"kaptchaCode");
//验证码文本长度
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH,"4");
//字体
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "宋体,楷体,微软雅黑");
Config config=new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
三、定义一个接口用来获取验证码图片的数据,然后把图片验证码的值保存在session中
@RestController
public class KaphtchaController {
@Autowired
private DefaultKaptcha defaultKaptcha;
/**
* @param httpServletRequest
* @param httpServletResponse
* @throws Exception
*/
@RequestMapping("/imageVerification")
public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws Exception {
byte[] captchaChallengeAsJpeg = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
// 生产验证码字符串并保存到session中,分布式环境存redis中
String createText = defaultKaptcha.createText();
httpServletRequest.getSession().setAttribute("vrifyCode", createText);
// 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
BufferedImage challenge = defaultKaptcha.createImage(createText);
ImageIO.write(challenge, "jpg", jpegOutputStream);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// 定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
httpServletResponse.setHeader("Cache-Control", "no-store");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
httpServletResponse.setContentType("image/jpeg");
ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
}
}
四、测试
地址:http://localhost:8080/imageVerification/