【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;
                }
            }
        })
    }

测试

相关推荐
程序员小刚5 分钟前
基于SpringBoot + Vue 的心理健康系统
vue.js·spring boot·后端
尚学教辅学习资料7 分钟前
基于SpringBoot+Vue的幼儿园管理系统+LW示例参考
vue.js·spring boot·后端·幼儿园管理系统
Python破壁人手记15 分钟前
《我的Python觉醒之路》之转型Python(十五)——控制流
java·服务器·开发语言·网络·python
Michaelwubo19 分钟前
jenkins 配置邮件问题整理
java·运维·jenkins
Moment31 分钟前
💯 铜三铁四,我收集整理了这些大厂面试场景题 (一)
前端·后端·面试
小安同学iter39 分钟前
SpringMVC(八)Knife4j 接口文档
java·开发语言·spring boot·spring·java-ee·intellij-idea
飞奔的马里奥41 分钟前
力扣Hot100——169. 多数元素
java·算法·leetcode
日暮南城故里1 小时前
Java学习------static、final、this、super关键字
java·学习
无名之逆1 小时前
轻量级、高性能的 Rust HTTP 服务器库 —— Hyperlane
服务器·开发语言·前端·后端·http·rust
无名之逆1 小时前
探索Hyperlane:用Rust打造轻量级、高性能的Web后端框架
服务器·开发语言·前端·后端·算法·rust