Java图片验证码的实现方法

一、后端实现

图片验证码都需要短时有效的,所以把验证码放到Redis中是不错的选择。

1.1 定义返回实体类对象:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CaptchaImageRespVO {

    @ApiModelProperty(value = "是否开启", required = true, example = "true", notes = "如果为 false,则关闭验证码功能")
    private Boolean enable;

    @ApiModelProperty(value = "uuid", example = "1b3b7d00-83a8-4638-9e37-d67011855968",
            notes = "enable = true 时,非空!通过该 uuid 作为该验证码的标识")
    private String uuid;

    @ApiModelProperty(value = "图片", notes = "enable = true 时,非空!验证码的图片内容,使用 Base64 编码")
    private String img;

}

1.2 获取验证码接口实现

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public CaptchaImageRespVO getImage() {
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(160, 60);
        CaptchaImageRespVO respVO = new CaptchaImageRespVO();
        respVO.setEnable(true);
        // 获得图片的Base64形式
        respVO.setImg(circleCaptcha.getImageBase64());

        String uuid = IdUtil.fastSimpleUUID();
        // 键 uuid,值 code,过期时间5分钟
        stringRedisTemplate.opsForValue().set(uuid, circleCaptcha.getCode(),5, TimeUnit.MINUTES);
        return respVO;
    }

1.3 登录逻辑

// 判断验证码是否正确,如果正确,要删除redis中的验证码

// 使用账号密码,进行登录

// 缓存登陆用户到 Redis 中,返回 sessionId 编号

二、前端实现 

// 获取验证码
export function getCodeImg() {
  return request({
    url: '/system/captcha/get-image',
    method: 'get',
    timeout: 20000
  })
}

"data:image/gif;base64," + res.img 

    getCode() {
      // 只有开启的状态,才加载验证码。默认开启
      if (!this.captchaEnable) {
        return;
      }
      // 请求远程,获得验证码
      getCodeImg().then((res) => {
        res = res.data;
        this.captchaEnable = res.enable;
        if (this.captchaEnable) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
<div class="login-code">
    <img :src="codeUrl" @click="getCode" class="login-code-img" />
</div>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值