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

测试

相关推荐
重生之后端学习17 分钟前
day08-Elasticsearch
后端·elasticsearch·spring cloud·中间件·全文检索·jenkins
东阳马生架构32 分钟前
订单初版—5.售后退货链路中的技术问题说明文档
java
小小寂寞的城37 分钟前
JAVA策略模式demo【设计模式系列】
java·设计模式·策略模式
志辉AI编程1 小时前
别人还在入门,你已经精通!Claude Code进阶必备14招
后端·ai编程
JAVA学习通1 小时前
图书管理系统(完结版)
java·开发语言
代码老y1 小时前
Spring Boot项目中大文件上传的高级实践与性能优化
spring boot·后端·性能优化
abigalexy1 小时前
深入Java锁机制
java
paishishaba1 小时前
处理Web请求路径参数
java·开发语言·后端
神仙别闹1 小时前
基于Java+MySQL实现(Web)可扩展的程序在线评测系统
java·前端·mysql
程序无bug1 小时前
Java中的8中基本数据类型转换
java·后端