• 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>

  • 相关阅读:
    速来围观,17个运维实用技巧
    vim安装AutoComplPop自动代码提示
    常用激活函数汇总
    什么是开源协议?开源协议的作用?
    【塔望咨询】×【紫燕食品】签署“紫燕·方便菜”品牌战略合作协议
    Python与CAD系列基础篇(七)创建单行、多行文本并修改样式
    钉钉智慧校园小程序如何开发,你知道么!
    黑马Java热门面试题MQ&Kafka(十一)
    2023-09-25 LeetCode每日一题(LFU 缓存)
    金仓数据库KingbaseES客户端编程接口指南-JDBC(12. 在应用服务器中配置JDBC)
  • 原文地址:https://blog.csdn.net/inexaustible/article/details/126507734