• Java图片验证码的实现方法


    一、后端实现

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

    1.1 定义返回实体类对象:

    1. @Data
    2. @Builder
    3. @NoArgsConstructor
    4. @AllArgsConstructor
    5. public class CaptchaImageRespVO {
    6. @ApiModelProperty(value = "是否开启", required = true, example = "true", notes = "如果为 false,则关闭验证码功能")
    7. private Boolean enable;
    8. @ApiModelProperty(value = "uuid", example = "1b3b7d00-83a8-4638-9e37-d67011855968",
    9. notes = "enable = true 时,非空!通过该 uuid 作为该验证码的标识")
    10. private String uuid;
    11. @ApiModelProperty(value = "图片", notes = "enable = true 时,非空!验证码的图片内容,使用 Base64 编码")
    12. private String img;
    13. }

    1.2 获取验证码接口实现

    1. import cn.hutool.captcha.CaptchaUtil;
    2. import cn.hutool.captcha.CircleCaptcha;
    3. import cn.hutool.core.util.IdUtil;
    1. @Resource
    2. private StringRedisTemplate stringRedisTemplate;
    3. @Override
    4. public CaptchaImageRespVO getImage() {
    5. CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(160, 60);
    6. CaptchaImageRespVO respVO = new CaptchaImageRespVO();
    7. respVO.setEnable(true);
    8. // 获得图片的Base64形式
    9. respVO.setImg(circleCaptcha.getImageBase64());
    10. String uuid = IdUtil.fastSimpleUUID();
    11. // 键 uuid,值 code,过期时间5分钟
    12. stringRedisTemplate.opsForValue().set(uuid, circleCaptcha.getCode(),5, TimeUnit.MINUTES);
    13. return respVO;
    14. }

    1.3 登录逻辑

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

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

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

    二、前端实现 

    1. // 获取验证码
    2. export function getCodeImg() {
    3. return request({
    4. url: '/system/captcha/get-image',
    5. method: 'get',
    6. timeout: 20000
    7. })
    8. }

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

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

  • 相关阅读:
    SpringMVC实训内容
    HTML5期末大作业:HTML+CSS茶叶官网网页设计实例 企业网站制作
    智慧化工园区管理平台综合解决方案
    idea配置tomcat的方法(详细图文步骤)
    数据结构(七)约瑟夫问题
    跨域问题解决方案(三种)
    web测试和app测试的区别?
    保障新能源园区安全无忧:可燃气体报警器校准检测的必要性探讨
    声网深度学习时序编码器的资源预测实践丨Dev for Dev 专栏
    python自动化运维——模拟键盘鼠标重复性操作Pyautoui
  • 原文地址:https://blog.csdn.net/inexaustible/article/details/126507734