图片验证码使用场景
- 登录注册:可以区分机器和人类的一种手段,其最大的作用是为了防止机器人程序暴力登录或攻击
- 短信发送:可以有效避免客户网站或APP遭到恶意攻击、预防资金损失
实现方式
1.添加Maven依赖
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
2.添加获取图片验证码接口
@ApiOperation("获取图片验证码")
@GetMapping("/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) {
commService.create(request, response);
}
注意:获取图片验证码时需要再请求地址后面加个参数key,key需保持唯一
3.实现方法
@Override
public void create(HttpServletRequest request, HttpServletResponse response) {
String key = request.getParameter("key");
if (StringUtils.isBlank(key)) {
throw new NingException(500,"请输入key码");
}
ValidateCodeProperties code = new ValidateCodeProperties();
setHeader(response, code.getType());
Captcha captcha = createCaptcha(code);
// 把验证码存进缓存中
dataCache.setCacheImageValidCode(key, StringUtils.lowerCase(captcha.text()));
try {
captcha.out(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
throw new NingException(500,"图形验证码生成失败,请稍后再试!");
}
}
private Captcha createCaptcha(ValidateCodeProperties code) {
Captcha captcha = null;
if (StringUtils.equalsIgnoreCase(code.getType(), "gif")) {
captcha = new GifCaptcha(code.getWidth(), code.getHeight(), code.getLength());
} else {
captcha = new SpecCaptcha(code.getWidth(), code.getHeight(), code.getLength());
}
captcha.setCharType(code.getCharType());
return captcha;
}
private void setHeader(HttpServletResponse response, String type) {
if (StringUtils.equalsIgnoreCase(type, "gif")) {
response.setContentType(MediaType.IMAGE_GIF_VALUE);
} else {
response.setContentType(MediaType.IMAGE_PNG_VALUE);
}
response.setHeader(HttpHeaders.PRAGMA, "No-cache");
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
response.setDateHeader(HttpHeaders.EXPIRES, 0L);
}
3.图片验证码配置类
@Data
public class ValidateCodeProperties {
/**
* 验证码有效时间,单位秒
*/
private Long time = 120L;
/**
* 验证码类型,可选值 png和 gif
*/
private String type = "png";
/**
* 图片宽度,px
*/
private Integer width = 130;
/**
* 图片高度,px
*/
private Integer height = 48;
/**
* 验证码位数
*/
private Integer length = 4;
/**
* 验证码值的类型
* 1. 数字加字母
* 2. 纯数字
* 3. 纯字母
*/
private Integer charType = 2;
}