SpringBoot实现验证码的案例分享

 更新时间:2024年11月04日 08:41:26   作者:vampire-wpre  
验证码可以有效防止其他人对某一个特定的注册用户用特定的程序,破解方式进行不断的登录尝试,我们其实很经常看到,登录一些网站其实是需要验证码的,所以本文给大家分享了SpringBoot实现验证码的案例,需要的朋友可以参考下

实现逻辑

1、后端功能:随机生成验证码图片,并把交给前端、接收用户输入,验证用户输入的验证码是否正确、

2、前端功能:显示验证码,提供输入框供用户输入他们看到的验证码,把用户输入的数据交给后端,接收后端返回的验证结果

前后端交互接口

后端需要完成的两个工作:1、生成验证码,2、校验验证码的正确性

接口定义:

1、生成验证码

请求url:/captcha/getCaptcha

响应:返回验证码的图片

2、校验验证码的正确性

请求url:/captcha/check

请求参数:用户输入的验证码captcha

响应:验证码正确返回true,错误返回false

前端代码

index.html

展示效果:

用户点击图片之后,可以更新验证码图片

在这里插入图片描述

代码如下:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="utf-8">
        <title>验证码</title>
        <style>
            body {
                font-family: 'Arial', sans-serif;
                background-color: #f7f7f7;
                margin: 0;
                padding: 0;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
            }
            #container {
                text-align: center;
                background: white;
                padding: 50px;
                border-radius: 8px;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            }
            h1 {
                color: #333;
                font-size: 2em;
                margin-bottom: 20px;
            }
            #inputCaptcha {
                height: 40px;
                margin-right: 10px;
                vertical-align: middle;
                border: 1px solid #ddd;
                border-radius: 4px;
                padding: 0 10px;
            }
            #verificationCodeImg {
                vertical-align: middle;
                border: 1px solid #ddd;
                cursor: pointer;
                transition: transform 0.2s;
            }
            #verificationCodeImg:hover {
                transform: scale(1.05);
            }
            #checkCaptcha {
                height: 40px;
                width: 120px;
                background-color: #5cb85c;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                transition: background-color 0.2s;
            }
            #checkCaptcha:hover {
                background-color: #4cae4c;
            }
        </style>
    </head>

    <body>
        <div id="container">
            <h1>输入验证码</h1>
            <div id="confirm">
                <input type="text" name="inputCaptcha" id="inputCaptcha">
                <img id="verificationCodeImg" src="http://127.0.0.1:8080/captcha/getCaptcha" style="cursor: pointer;"
                     title="看不清?换一张"/>
                <input type="button" value="提交" id="checkCaptcha">
            </div>
        </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', 'http://127.0.0.1:8080/captcha/getCaptcha?dt=' + new Date().getTime()).fadeIn();
            });

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

</html>

success.html,当用户验证码输入正确时展示的内容

展示效果:

在这里插入图片描述

代码如下:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>验证成功页</title>
        <style>
            body {
                font-family: 'Arial', sans-serif;
                background-color: #f7f7f7;
                margin: 0;
                padding: 0;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
            }
            .container {
                text-align: center;
                background: white;
                padding: 50px;
                border-radius: 8px;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            }
            h1 {
                color: green;
                font-size: 2.5em;
                margin: 0;
            }
            p {
                color: blue;
                font-size: 1.2em;
                margin-top: 20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>验证成功</h1>
        </div>
    </body>
</html>

后端代码

结构如下:

在这里插入图片描述

在pom.xml中添加依赖:

在这里插入图片描述

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-captcha</artifactId>
    <version>5.8.26</version>
</dependency>

CaptchaController类:

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    //注入
    @Autowired
    private CaptchaProperties captchaProperties;

    @Value("${captcha.session.key}")
    private String key;
    @Value("${captcha.session.datetime}")
    private String datetime;


    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());

        String code = lineCaptcha.getCode();

        //设置session,把验证码信息存储到session中
        session.setAttribute(key, code);
        session.setAttribute(datetime, new Date());


        //验证码写入浏览器
        lineCaptcha.write(response.getOutputStream());

        //设置ContentType
        response.setContentType("image/jpeg");
        //设置编码
        response.setCharacterEncoding("utf8");
        //防止浏览器缓存验证码图片
        response.setHeader("Pragma", "No-cache");

    }

    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session) {
        String code = (String) session.getAttribute(key);


        if (!StringUtils.hasLength(captcha)) {
            return false;
        }

        //从session中获取时间
        Date date = (Date) session.getAttribute(datetime);

        if (date == null || System.currentTimeMillis() - date.getTime() > 60 * 1000) {
            //session为null,或者session过期(超过一分钟就算过期)
            //System.currentTimeMillis() - date.getTime(): 当前时间-请求时间
            return false;
        }

        //不区分大小写
        return captcha.equalsIgnoreCase(code);
    }
}

CaptchaProperties类:

@ConfigurationProperties(prefix = "captcha")
@Configuration
@Data
public class CaptchaProperties {
    private Integer height;
    private Integer width;

}

MySession类:

@Data
public class MySession {
    private String key;
    private String datetime;
}

配置文件 application.yml:

captcha:
  height: 50
  width: 150
  session:
    key: CaptchaCode
    datetime: CaptchaDate

以上就是SpringBoot实现验证码的案例分享的详细内容,更多关于SpringBoot验证码案例的资料请关注脚本之家其它相关文章!

相关文章

  • 初次体验MyBatis的注意事项

    初次体验MyBatis的注意事项

    今天给大家带来的是关于MyBatis的相关知识,文章围绕着MyBatis的用法展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下
    2021-06-06
  • Myeclipse 2016下Aptana安装教程

    Myeclipse 2016下Aptana安装教程

    这篇文章主要为大家详细介绍了Myeclipse 2016下Aptana安装教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05
  • Quarkus中实现Resteasy的文件上传下载操作

    Quarkus中实现Resteasy的文件上传下载操作

    这篇文章主要为大家介绍了Quarkus中实现Resteasy的文件上传下载的操作过程步骤,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2022-02-02
  • Java实现学生管理系统详解流程

    Java实现学生管理系统详解流程

    这篇文章主要为大家详细介绍了如何利用Java语言实现学生管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-06-06
  • SpringBoot拦截器读取流后不能再读取的问题

    SpringBoot拦截器读取流后不能再读取的问题

    这篇文章主要介绍了SpringBoot拦截器读取流后不能再读取的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • Java数组和可变参数使用举例详解

    Java数组和可变参数使用举例详解

    Java中的可变参数和数组参数在使用上很相似,但它们在方法定义、调用方式以及编译处理上有明显区别,理解这些差异有助于写出更清晰、安全的代码,这篇文章主要介绍了Java数组和可变参数的相关资料,需要的朋友可以参考下
    2026-05-05
  • 详解java动态代理的2种实现方式

    详解java动态代理的2种实现方式

    目前Java开发包中包含了对动态代理的支持,但是其实现只支持对接口的的实现。这篇文章主要介绍了详解java动态代理的2种实现方式 ,有兴趣的可以了解一下。
    2016-11-11
  • 关于服务网关Spring Cloud Zuul(Finchley版本)

    关于服务网关Spring Cloud Zuul(Finchley版本)

    这篇文章主要介绍了关于服务网关Spring Cloud Zuul(Finchley版本),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • 解决	Spring RestTemplate post传递参数时报错问题

    解决 Spring RestTemplate post传递参数时报错问题

    本文详解说明了RestTemplate post传递参数时报错的问题及其原由,需要的朋友可以参考下
    2020-02-02
  • Java中StopWatch工具类的用法详解

    Java中StopWatch工具类的用法详解

    stopWatch 是org.springframework.util 包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比,下面就跟随小编一起来看看它的具体用法吧
    2024-12-12

最新评论