【spring boot 实现图片验证码 前后端】

导入hutool依赖

复制代码
		<!--hutool-->
		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>5.8.36</version>

获取验证码接口

java 复制代码
    @Autowired
    private Captcha captcha;
    private final static Long VALIDATE_CODE = 60 * 1000L;
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        // 设置响应内容类型
        response.setContentType("image/png");
        // 直接把验证码写入浏览器,没有返回值
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captcha.getWidth(), captcha.getHeight(),4,4);
        String code = lineCaptcha.getCode();
        session.setAttribute(captcha.getSession().getKey(), code);
        session.setAttribute(captcha.getSession().getDate(),new Date());// 获取当前时间
        lineCaptcha.write(response.getOutputStream());
    }

检查验证码接口

java 复制代码
    @RequestMapping("/check")
    public boolean check(String mycaptcha, HttpSession session) {
        System.out.println("[captchaCheck]用户输入的验证码:" + mycaptcha);
        String code = (String)session.getAttribute(captcha.getSession().getKey());
        if(!StringUtils.hasLength(code)) {
            return false;
        }
        Date date = (Date)session.getAttribute(captcha.getSession().getDate());
        if(mycaptcha.equalsIgnoreCase(code) && VALIDATE_CODE >= System.currentTimeMillis() - date.getTime()) {
            return true;
        }
        return false;
    }

前后端交互

html 复制代码
<img id="captcha_img" src="/captcha/getCaptcha" alt="看不清?换一张" onclick="change()">
js 复制代码
let check = false;
    function change() {
        event.preventDefault();  // 阻止表单默认提交行为
        $.ajax({
            type: "get",
            url: "/captcha/getCaptcha",
            success: function (result) {
                console.log("[getCaptcha]刷新的验证码:" + result);
                $("#captcha_img").attr("src", "/captcha/getCaptcha");
            }
        })
    }
    function login() {
        event.preventDefault();  // 阻止表单默认提交行为
        $.ajax({
            type: "get",
            url: "/login",
            data: {
                username: $("#username").val(),
                password: $("#password").val(),
            },
            success: function (result) {
                console.log(result);
                if(result === false) {
                    alert("用户名或密码错误!!");

                }
                else if(result === true && check === false) {
                    alert("验证码错误!!");
                    location.reload();
                }
                else if(result === true && check === true) {
                    location.href = "recognize.html";
                }
                // if(result === true && check === true) {
                //     location.href = "recognize.html";
                // }
                // else {
                //     alert("用户名或密码错误!!");
                // }
            }
        })
        $.ajax({
            type: "post",
            url: "/captcha/check",
            data: {
                mycaptcha: $("#captcha").val() 
            },
            success: function (result) {
                console.log(result);
                if(result === false) {
                    check = false;
                    // alert("验证码错误!!");
                    // location.reload();
                }  
                else {
                    check = true;
                }
            }
        })
    }

测试

相关推荐
掘金者阿豪几秒前
接口数据传输优化实战:JSON Gzip 与 Protobuf 的深度对比
后端
存在morning几秒前
【PySpark 学习笔记 三】DataFrame API 入门
android·java·数据库
用户608186527901 分钟前
Avalonia UI 样式进阶实战:外置样式 + MVVM 主题切换 + 样式优先级全解析
后端
AC赳赳老秦3 分钟前
企业标签体系搭建:基于 OpenClaw 采集的多维度公开数据,构建企业画像标签库
java·运维·服务器·python·信息可视化·deepseek·openclaw
智嵌研习社6 分钟前
Ollama 本地大模型完全配置指南:Modelfile 参数与系统环境变量深度解析
java·开发语言
掘金者阿豪13 分钟前
达梦VS金仓:真正做一次Oracle迁移,才知道工具链有多重要
后端
刘立军13 分钟前
中心化配置与 I18n:严格禁止 AI 魔法值与硬编码参数
人工智能·后端·架构
Y0011123617 分钟前
springboot+vue项目实战
vue.js·spring boot·后端
Csvn22 分钟前
📊 SQL 入门 Day 25:查询优化实战 —— 从 EXPLAIN 到索引的完整排查流
后端·sql
用户2986985301422 分钟前
将 Excel 表格转换为图片的三种实用方法
人工智能·后端·excel