基于SpringBoot-验证码

文章目录


前言

每当我们登录时,大多数平台都会有验证码验证,那么在开发过程中是如何实现的呢!接下来这篇文章就让我们一起学习下在Java后端开发中是如何实现的!


一、前端文件放置

二、约定前后端交互接口

1.需求分析

后端需要提供两个服务

(1)生成验证码,并返回验证码

(2)校验验证码是否正确

2.接口的定义

(1)生成验证码

请求:

c 复制代码
请求URL:/captcha/getCaptcha

响应:验证码图片内容(即浏览器给服务器发送一个/captcha/getCaptcha这样的请求,服务器返回一个图片,浏览器显示在页面上)

(2)校验验证码是否正确

请求:/captcha/check

c 复制代码
请求URL:/captcha/check
请求参数:captcha=xn8d

响应:

c 复制代码
true

根据用户输入的验证码,校验验证码是否正确,true:验证成功,false:验证失败

三、Hutool工具介绍

Hutool是⼀个Java⼯具包类库,对⽂件、流、加密解密、转码、正则、线程、XML等JDK⽅法进⾏封

装,组成各种Util⼯具类.

Hutool是⼀个⼩⽽全的Java⼯具类库,通过静态⽅法封装,降低相关API的学习成本,提⾼⼯作效

率,使Java拥有函数式语⾔般的优雅,让Java语⾔也可以"甜甜的"

lHutool图形验证码网络地址

四、代码实现

1.服务器端代码实现

(1)引入依赖

bash 复制代码
<dependency>
   <groupId>cn.hutool</groupId>
   <artifactId>hutool-captcha</artifactId>
   <version>5.8.22</version>
</dependency>

(2)后端代码

HuToolCaptchaController.java

java 复制代码
package org.example.springbootdemo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.springbootdemo.model.CaptchaProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class HuToolCaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/getCaptcha")
    public void getCode(HttpSession session, HttpServletResponse response) {
        //定义图形验证码的⻓和宽

        LineCaptcha lineCaptcha =
                CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),
                        captchaProperties.getHeight());
        response.setContentType("image/jpeg");
        //禁⽌使⽤缓存

        response.setHeader("Pragma", "No-cache");
        try {
            //输出到⻚⾯

            lineCaptcha.write(response.getOutputStream());
            //存储在Session中

            session.setAttribute(captchaProperties.getSession().getKey(),
                    lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());
            //打印⽇志
            System.out.println("⽣成的验证码:" + lineCaptcha.getCode());
//关闭流

            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private final static long VALID_MILLIS_TIME = 60 * 1000;
    @RequestMapping("/check")
    public boolean checkHomeCaptcha(String captcha, HttpSession session) {
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }
        String savedCaptcha = (String)
                session.getAttribute(captchaProperties.getSession().getKey());
        Date sessionDate = (Date)
                session.getAttribute(captchaProperties.getSession().getDate());
        if (captcha.equalsIgnoreCase(savedCaptcha)) {
            if (sessionDate == null
                    || System.currentTimeMillis() - sessionDate.getTime() <
                    VALID_MILLIS_TIME) {
                return true;
            }
            return false;
        }
        return false;
    }
}

CaptchaProperties.java

java 复制代码
package org.example.springbootdemo.model;

import jakarta.websocket.Session;
import lombok.Data;
import lombok.Getter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "captcha")
public class CaptchaProperties {
    private Integer width;
    private Integer height;
    private Session session;
    @Data
    public static class Session {
        private String key;
        private String date;
    }
}

Session.java

java 复制代码
package org.example.springbootdemo.model;

import lombok.Data;

@Data
public class Session {
    private String code;
    private String date;
}

2.客户端代码实现

(1)index.html

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">

  <title>验证码</title>
  <style>
    #inputCaptcha {
      height: 30px;
      vertical-align: middle;
    }
    #verificationCodeImg{
      vertical-align: middle;
    }
    #checkCaptcha{
      height: 40px;
      width: 100px;
    }
  </style>
</head>

<body>
<h1>输入验证码</h1>
<div id="confirm">
  <input type="text" name="inputCaptcha" id="inputCaptcha">
  <img id="verificationCodeImg" src="/captcha/getCaptcha" style="cursor: pointer;" title="看不清?换一张" />
  <input type="button" value="提交" id="checkCaptcha">
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>

  $("#verificationCodeImg").click(function(){
    $(this).hide().attr('src', '/captcha/getCaptcha?dt=' + new Date().getTime()).fadeIn();
  });

  $("#checkCaptcha").click(function () {
    // alert("验证码校验");
    $.ajax({
      type: "post",
      url: "/captcha/check",
      data: {
        captcha: $("#inputCaptcha").val()
      },
      success: function(result){
        if(result){
          location.href = "success.html";
        }else{
          alert("验证码错误");
        }
      }
    });
  });

</script>
</body>

</html>

(2)success.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>验证成功页</title>
</head>
<body>
    <h1>验证成功</h1>
</body>
</html>

五、运行结果


总结

验证码功能在Java后端开发中主要通过Hutool工具库实现,分为生成和校验两个核心模块。

生成验证码接口

通过/captcha/getCaptcha接口返回图形验证码,利用Hutool的LineCaptcha生成包含随机字符的图片。生成的验证码会存储到Session中,并设置有效期(示例为60秒),同时通过响应流将图片返回给前端显示。

校验验证码接口
/captcha/check接口接收用户输入的验证码,与Session中存储的验证码进行比对(不区分大小写),并检查是否在有效期内。校验结果返回布尔值,前端根据结果进行相应处理。

技术要点

  • 使用Hutool的CaptchaUtil快速生成图形验证码
  • 通过Session存储验证码和生成时间
  • 验证码有效期控制增强安全性
  • 前后端分离设计,接口返回简单JSON或图片数据

这种实现方式兼顾了开发效率和安全性,适用于大多数Web应用的验证需求。通过配置类管理验证码参数(如宽高、Session键名等),提高了代码的可维护性。

相关推荐
我爱娃哈哈2 小时前
SpringBoot + ELK + MDC:分布式系统日志追踪,快速定位跨服务调用链问题
spring boot·后端·elk
lvbinemail2 小时前
配置jenkins.service
java·运维·jenkins·systemctl
ss2732 小时前
若依分离版后端集成 Camunda 7 工作流引擎
java·若依
明天…ling2 小时前
sql注入(1-10关)
java·数据库·sql
Ashley_Amanda2 小时前
SAP调用Web Service全流程详解
java·前端·数据库
笨手笨脚の2 小时前
Linux JDK NIO 源码分析
java·linux·nio
顾北122 小时前
RAG 入门到实战:Spring AI 搭建旅游问答知识库(本地 + 阿里云百炼双方案)
java·人工智能·阿里云
chilavert3182 小时前
技术演进中的开发沉思-329 JVM:垃圾回收(中)
java·jvm·算法
難釋懷2 小时前
隐藏用户敏感信息
java·spring boot