springboot怎么集成easy-captcha实现图像验证码显示和登录
1、easy-captcha简介
easy-captcha是生成图形验证码的Java类库,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目。

2、添加依赖
20.0 1.6.2 com.google.guava guava ${guava.version} com.github.whvcse easy-captcha ${captcha.version}
3、编写service层代码
@Service
public class CaptchaServiceImpl implements CaptchaService {
/**
* Local Cache 5分钟过期
*/
Cache localCache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterAccess(5, TimeUnit.MINUTES).build();
@Override
public void create(HttpServletResponse response, String uuid) throws IOException {
response.setContentType("image/gif");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//生成验证码
SpecCaptcha captcha = new SpecCaptcha(150, 40);
captcha.setLen(5);
captcha.setCharType(Captcha.TYPE_DEFAULT);
captcha.out(response.getOutputStream());
//保存到缓存
setCache(uuid, captcha.text());
}
@Override
public boolean validate(String uuid, String code) {
//获取验证码
String captcha = getCache(uuid);
//效验成功
if(code.equalsIgnoreCase(captcha)){
return true;
}
return false;
}
private void setCache(String key, String value){
localCache.put(key, value);
}
private String getCache(String key){
String captcha = localCache.getIfPresent(key);
//删除验证码
if(captcha != null){
localCache.invalidate(key);
}
return captcha;
}
} 4、开发验证码接口
创建LoginController并提供生成验证码的方法
@Controller
@AllArgsConstructor
public class CaptchaController {
private CaptchaService captchaService;
@GetMapping("/captcha")
public void captcha(HttpServletResponse response, String uuid)throws IOException {
//uuid不能为空
AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL);
//生成验证码
captchaService.create(response, uuid);
}
}5、前端vue增加如何代码显示生成的验证码
完整的登录页代码如下
![]()
{{ title }}
![]()
登录
编译运行后端,同事运行点前端,可以看到登录页面。