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

测试

相关推荐
典孝赢麻崩乐急9 分钟前
Java学习---JVM(1)
java·jvm·学习
Xiao_zuo_ya15 分钟前
SpringBoot-Freemarker导出word
spring boot·word
m0_5973453118 分钟前
【Android】安卓四大组件之广播接收器(Broadcast Receiver):从基础到进阶
android·java·boradcast·安卓四大组件
程序员的世界你不懂19 分钟前
基于Java+Maven+Testng+Selenium+Log4j+Allure+Jenkins搭建一个WebUI自动化框架(5)失败用例截图与重试
java·selenium·maven
一块plus31 分钟前
深度详解 Revive 和 Precompile 技术路径
后端·设计模式·架构
iOS开发上架哦35 分钟前
没有Mac如何完成iOS 上架:iOS App 上架App Store流程
后端
喧星Aries36 分钟前
进程调度的时机,切换与过程方式(操作系统OS)
java·服务器·前端·操作系统·进程调度
晴空月明36 分钟前
分布式系统高可用性设计-负载均衡与容错机制深度解析
后端
JouJz37 分钟前
Spring事务管理深度解析:原理、实践与陷阱
java·spring
此乃大忽悠40 分钟前
身份认证缺陷
java·数据库·webgoat·身份认证缺陷