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

  • 相关阅读:
    常用排序算法
    应用软件安全保证措施方案书
    Python实现点击选择验证码破解
    Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【六】
    HTML静态网页成品作业(HTML+CSS)——家乡芷江侗族自治县介绍网页(1个页面)
    redis底层都有哪些数据结构?带你了解redis是如何存储数据的
    Vue之ElementUI实现登陆及注册
    基于PHP+MySQL的个人博客系统毕设
    从一个页面跳转到目标页面之后,对应的顶部路由高亮
    编译构建 meson ninja
  • 原文地址:https://blog.csdn.net/inexaustible/article/details/126507734