Picture verification code usage scenarios
- Login registration: A means to distinguish between machines and humans. Its greatest role is to prevent violent login or attacks by robot programs
- SMS sending: It can effectively avoid malicious attacks on customer websites or APPs and prevent financial losses
Method to realize
1. Add Maven dependency
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
2. Add an interface for obtaining image verification codes
@ApiOperation("获取图片验证码")
@GetMapping("/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) {
commService.create(request, response);
}
Note: When obtaining the image verification code, you need to add a parameter key after the request address , and the key must be unique
3. Implementation method
@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. Image verification code configuration class
@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;
}