Java代码如何生成图形验证码(gif、中文、算术)呢?
下文笔者讲述java代码生成复杂的图形验证码的方法分享,如下所示
图形验证码简介
图形验证码:
是所有网站都必备的一种验证方式
那么如何生成一种验证码,里面可包含(中文、算术)的信息呢?
下文将一一道来,如下所示
java生成图形验证码的实现思路
可借助EasyCaptcha 1.引入jar包 2.定义SpecCaptcha对象即可生成一个随机验证码例:
1.maven项目引入easy-captcha
<dependencies>
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
2.SpringBoot项目创建图形验证码
存入Redis设置缓存时间
并返回验证码信息
@Controller
public class CaptchaController {
@Autowired
private RedisUtil redisUtil;
@ResponseBody
@RequestMapping("/vcode/captcha")
public JsonResult captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
String verCode = specCaptcha.text().toLowerCase();
String key = UUID.randomUUID().toString();
// 存入redis并设置过期时间为30分钟
redisUtil.setEx(key, verCode, 30, TimeUnit.MINUTES);
// 将key和base64返回给前端
return JsonResult.ok().put("key", key).put("image", specCaptcha.toBase64());
}
@ResponseBody
@PostMapping("/vcode/vaild")
public JsonResult login(String username,String password,String verCode,String verKey){
// 获取redis中的验证码
String redisCode = redisUtil.get(verKey);
// 判断验证码
if (verCode==null || !redisCode.equals(verCode.trim().toLowerCase())) {
return JsonResult.error("验证码不正确");
}
}
}
//3.前端使用ajax获取验证码并验证
<img id="imgCode" width="130px" height="48px"/>
<script>
var verKey;
// 获取验证码
$.get('/vcode/captcha', function(res) {
verKey = res.key;
$('#imgCode').attr('src', res.image);
},'json');
</script>
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


