您的位置 首页 java

Java图形验证码支持gif、中文、算术等

图形验证码是最经典,也是最常用的验证方式。今天介绍一个非常不错的类库: Java 图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目。

官网:

 
  

效果图:

Java图形验证码支持gif、中文、算术等


0x01:项目引入easy-captcha

 <dependencies>
   <dependency>
      <groupId>com. github .whvcse</groupId>
      <artifactId>easy-captcha</artifactId>
      <version>1.6.2</version>
   </dependency>
</dependencies>
  

0x02:SpringBoot项目创建图形验证码

前后端分离项目中建议不要存储在 session 中;而使用分布式session,存储在 redis 中,redis存储需要一个key,key一同返回给前端用于验证输入。

 @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("验证码不正确");
        }
    }  
}
  


0x03: 前端使用 ajax 获取验证码并验证

 <img id="verImg" width="130px" height="48px"/>

<script>
    var verKey;
    // 获取验证码
    $.get('/vcode/captcha',  function (res) {
        verKey = res.key;
        $('#verImg').attr('src', res.image);
    },'json');

    // 登录
    $.post('/vcode/login', {
        verKey: verKey,
        verCode: '8u6h',
        username: 'admin',
        password: 'admin'
    }, function(res) {
        console.log(res);
    }, 'json');
</script>  

文章来源:智云一二三科技

文章标题:Java图形验证码支持gif、中文、算术等

文章地址:https://www.zhihuclub.com/201082.shtml

关于作者: 智云科技

热门文章

网站地图