验证码案例

目录

前言

一、Hutool工具介绍

1.1 Maven 

1.2 介绍

1.3 实现类 

二、验证码案例

2.1 需求

2.2 约定前后端交互接口

2.2.1 需求分析

2.2.2 接口定义

2.3 后端生成验证码

2.4 前端接收验证码图片

2.5 后端校验验证码

2.6  前端校验验证码

2.7 后端完整代码 


前言

        验证码实现方式很多,可以前端实现,也可以后端实现,网上也有比较多的插件或者工具包可以使用,咱们选择使用Hutool提供的小工具来实现。

一、Hutool工具介绍

        Hutool是一个Java工具包类库,对文件、流、加密解密、转码、正则、线程、XML等JDK方法进行封装,组成各种Util工具类。Hutool官网:https://hutool.cn/

1.1 Maven 

如果你想在项目中使用Hutool中的某个模块,在项目的pom.xml的dependencies中加入以下内容:

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

1.2 介绍

验证码功能位于cn.hutool.captcha包中,核心接口为ICaptcha,此接口定义了以下方法:

  • createCode 创建验证码,实现类需同时生成随机验证码字符串和验证码图片
  • getCode 获取验证码的文字内容
  • verify 验证验证码是否正确,建议忽略大小写
  • write 将验证码图片写出到目标流中

其中write方法只有一个OutputStreamICaptcha实现类可以根据这个方法封装写出到文件等方法。

AbstractCaptcha为一个ICaptcha抽象实现类,此类实现了验证码文本生成、非大小写敏感的验证、写出到流和文件等方法,通过继承此抽象类只需实现createImage方法定义图形生成规则即可。 

1.3 实现类 

LineCaptcha线段干扰的验证码

贴栗子:

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;

public class LineCaptchaTest {
    public static void main(String[] args) {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        //图形验证码写出,可以写出到文件,也可以写出到流
        lineCaptcha.write("d:/line.png");
        //输出code
        Console.log(lineCaptcha.getCode());
        //验证图形验证码的有效性,返回boolean值
        lineCaptcha.verify("1234");

        //重新生成验证码
        lineCaptcha.createCode();
        lineCaptcha.write("d:/line.png");
        //新的验证码
        Console.log(lineCaptcha.getCode());
        //验证图形验证码的有效性,返回boolean值
        lineCaptcha.verify("1234");
    }
}

控制台截图生成的验证码:

 

在写入的路径中查看代码生成的验证码截图:

CircleCaptcha 圆圈干扰验证码 

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.lang.Console;

public class CircleCaptchaTest {
    public static void main(String[] args) {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        //CircleCaptcha captcha = new CircleCaptcha(200, 100, 4, 20);
        //图形验证码写出,可以写出到文件,也可以写出到流
        captcha.write("d:/circle.png");
        //输出code
        Console.log(captcha.getCode());
        //验证图形验证码的有效性,返回boolean值
        captcha.verify("1234");
    }
}

 控制台截图生成的验证码:

 在写入的路径中查看代码生成的验证码截图:

ShearCaptcha 扭曲干扰验证码 

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.lang.Console;

public class ShearCaptchaTest {
    public static void main(String[] args) {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
        //ShearCaptcha captcha = new ShearCaptcha(200, 100, 4, 4);
        //图形验证码写出,可以写出到文件,也可以写出到流
        captcha.write("d:/shear.png");
        //输出code
        Console.log(captcha.getCode());
        //验证图形验证码的有效性,返回boolean值
        captcha.verify("1234");
    }
}

控制台截图生成的验证码:

在写入的路径中查看代码生成的验证码截图:

二、验证码案例

2.1 需求

需求如下:

  • 页面生成验证码
  • 输入验证码,点击提交,验证用户输入验证码是否正确,正确则进行页面跳转

2.2 约定前后端交互接口

2.2.1 需求分析

后端需要提供两个服务:

  • 生成验证码,并返回验证码
  • 校验验证码是否正确

2.2.2 接口定义

1、生成验证码:

url:/captcha/get

param:无

return:图片的内容

2、校验验证码

url:/captcha/check

param:inputCode

return:true/false

2.3 后端生成验证码

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse response) {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        //图像验证码写出,可以写出到文件,也可以写出到流,此处写出到流
        try {
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

小技巧:在我们每写完一个后端代码模块时,我们可以进行测试,看是否有错误,避免后续代码量过多发生错误时不知道哪块出错。

根据后端定义的url进行测试截图:

2.4 前端接收验证码图片

<!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/get" 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/get?dt=' + new Date().getTime()).fadeIn();
    });

    $("#checkCaptcha").click(function () {
        alert("验证码校验");
    });

  </script>
</body>

</html>

验证前端是否有问题:

2.5 后端校验验证码

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.demo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private final static long session_valid_timeout = 60 * 1000;

    @Autowired
    private CaptchaProperties captchaProperties;
    
    @RequestMapping("/check")
    public Boolean check(HttpSession session, String inputCode) {
        //验证码输入的内容和用户输入的进行比较
        //从session获取信息
        if (!StringUtils.hasLength(inputCode)) {
            return false;
        }
        String savedCode = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date saveDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        if (inputCode.equalsIgnoreCase(savedCode)) {
            //判断验证码是否过期
            if (saveDate != null && System.currentTimeMillis() - saveDate.getTime() < session_valid_timeout) {
                return true;
            }
            return true;
        }
        return false;
    }
}

检查校验验证码是否存在问题:

1、先查看后端生成的验证码

2、根据校验验证的url进行验证

        首先先输入错误的验证码观察返回ture或者false,如果返回false证明验证码输入错误或者过期,否则反正true。

先输入错误的验证码1234截图:

再输入正确的验证码截图:

2.6  前端校验验证码

<!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/get" 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/get?dt=' + new Date().getTime()).fadeIn();
    });

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

  </script>
</body>

</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>

运行截图:

 

 

2.7 后端完整代码 

package com.example.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.demo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private final static long session_valid_timeout = 60 * 1000;

    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/get")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        //设置缓存类型
        response.setContentType("image/jpeg");
        //禁止缓存
        response.setHeader("Progma", "No-cache");
        //图像验证码写出,可以写出到文件,也可以写出到流,此处写出到流
        try {
            lineCaptcha.write(response.getOutputStream());
            //存储session
            session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public Boolean check(HttpSession session, String inputCode) {
        //验证码输入的内容和用户输入的进行比较
        //从session获取信息
        if (!StringUtils.hasLength(inputCode)) {
            return false;
        }
        String savedCode = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date saveDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        if (inputCode.equalsIgnoreCase(savedCode)) {
            //判断验证码是否过期
            if (saveDate != null && System.currentTimeMillis() - saveDate.getTime() < session_valid_timeout) {
                return true;
            }
        }
        return false;
    }
}

配置文件:

captcha:
  width: 200
  height: 100
  session:
    key: captcha_session_key
    date: captcha_session_date

captcha配置:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

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

    @Data
    public static class Session {
        private String key;
        private String date;
    }
}

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/691075.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

vue项目搭建

目录 引入依赖1. elementa. notifyb. el-dropdown-item绑定点击事件点击无效c. 页面重新加载d. 路由新页面打开e.Scrollbar 滚动条 2. main.js模板3.axios post请求参数4. 数据保存在本地5. mavon-editor6. 获得路由参数7.远程搜索8.参数传入自定义参数9.固定屏幕不动10.有时事…

Elasticsearch 认证模拟题 - 14

一、题目 在集群中输入以下指令&#xff1a; PUT phones/_doc/1 {"brand":"Samsumg","model":"Galaxy S9","features":[{"type":"os", "value":"Android"},{"type":&q…

Edge怎么关闭快捷键

Edge怎么关闭快捷键 在Edge浏览器中&#xff0c;你可以通过以下步骤关闭快捷键&#xff1a; 打开Edge浏览器&#xff0c;输入&#xff1a;edge://flags 并按下回车键。 在Flags页面中&#xff0c;搜索“快捷键”(Keyboard shortcuts)选项。 将“快捷键”选项的状态设置为“…

【SpringBoot】项目搭建基本步骤(整合 Mybatis)

搭建 SpringBoot 项目有两种方式&#xff1a;使用 IDEA、或者在 Spring 官网下载。 1. IDEA 创建 打开 IDEA 后&#xff0c;英文版请点击 File -> New -> Project -> Spring Initialer。 中文版请点击 文件 -> 新建 -> 项目 -> Spring Initialer。 在打开的…

老师如何制作高考后志愿填报信息采集系统?

高考结束后&#xff0c;志愿填报成为学生们的头等大事。面对众多选择&#xff0c;如何高效、准确地填报志愿&#xff0c;是每个学生和家长都关心的问题。作为老师&#xff0c;能否利用现有的技术工具&#xff0c;帮助学生更好地完成志愿填报呢&#xff1f; 老师们需要一个能够…

机器学习作业6——svm支持向量机

目录 一、理论 概念&#xff1a; 线性可分&#xff1a; 支持向量&#xff1a; 间隔&#xff1a; 目标&#xff1a; 软间隔&#xff1a; 梯度下降法&#xff1a; 别的方法&#xff1a; 拉格朗日函数&#xff1a; SMO算法&#xff1a; 核函数&#xff1a; 二、代码 …

Zemax中FFT PSF和惠更斯PSF的区别?

在Zemax“分析”选项卡中&#xff0c;有PSF&#xff08;“点扩散函数”&#xff09;图&#xff0c;主要包括如下两种计算方式&#xff1a; 1. FFT PSF&#xff0c;快速傅里叶变换&#xff08;fast fourier transform&#xff0c;FFT&#xff09; 该方法可以看做是以下点扩散函…

【录制,纯正人声】OBS录制软件,音频电流音,杂音解决办法,录制有噪声的解决办法

速度解决的方法 &#xff08;1&#xff09;用RNNoise去除噪声。RNNoise是一个开源的&#xff0c;效果不好的噪声去除器。使用方法就是点击滤镜&#xff0c;然后加噪声抑制RNNoise。【这方法不好用】 &#xff08;2&#xff09;用Krisp(https://krisp.ai/) 去除噪声。这个Kris…

华为云服务器-云容器引擎 CCE环境构建及项目部署

1、切换地区 2、搜索云容器引擎 CCE 3、购买集群 4、创建容器节点 通过漫长的等待(五分钟左右)&#xff0c;由创建中变为运行中&#xff0c;则表明容器已经搭建成功 购买成功后&#xff0c;返回容器控制台界面 5、节点容器管理 6、创建redis工作负载 7、创建mysql工作负载 8、…

有效的括号(oj题)

一、题目链接 https://leetcode.cn/problems/valid-parentheses/submissions/538110206 二、题目思路 利用栈的性质&#xff0c;后进先出 1.依次读取字符串&#xff0c;判断是否为左括号&#xff0c;如果是&#xff0c;就将其入栈。 2.如果读取的不是左括号&#xff0c;就说…

c++编译器在什么情况下会提供类的默认构造函数等,与析构函数

我们都知道&#xff0c;在 c 里&#xff0c;编写的简单类&#xff0c;若没有自己编写构造析构函数与 copy 构造函数 与 赋值运算符函数&#xff0c;那么编译器会提供这些函数&#xff0c;并实现简单的语义&#xff0c;比如成员赋值。看 源码时&#xff0c;出现了下图类似的情形…

如何使用Python的Turtle模块绘制小猪

一、前置条件 在开始学习如何使用Python的Turtle模块进行绘画之前&#xff0c;请确保你的电脑已安装Python环境。如果尚未安装Python&#xff0c;你可以从Python官网下载并安装最新版本。 Turtle模块是Python内置的一个用于绘图的库&#xff0c;通常不需要额外安装。如果你发…

vivado DIAGRAM、HW_AXI

图表 描述 块设计&#xff08;.bd&#xff09;是在IP中创建的互连IP核的复杂系统 Vivado设计套件的集成商。Vivado IP集成器可让您创建复杂的 通过实例化和互连Vivado IP目录中的IP进行系统设计。一块 设计是一种分层设计&#xff0c;可以写入磁盘上的文件&#xff08;.bd&…

【TB作品】MSP430F5529 单片机,数字时钟设计与实现,整点时通过蜂鸣器播放音乐进行报时

基于单片机的数字时钟设计与实现 作品名称 基于MSP430单片机的OLED显示数字时钟 作品功能 本作品实现了一个具有时间显示和整点报时功能的数字时钟。通过OLED屏幕显示当前时间&#xff0c;用户可以通过按键设置时间&#xff0c;并在整点时通过蜂鸣器播放音乐进行报时。 作…

vue处理json数据

背景&#xff1a;后端返回的数据不是我想要的&#xff0c;现在需要把 name 替换为title&#xff08;小声蛐蛐&#xff1a;又让我处理数据&#xff09; 后端返回数据格式 修改字段操作&#xff1a;&#xff08;使用递归遍历的方式将title属性赋了name的值&#xff09; renderT…

八、【源码】细化XML语句构建器,完善静态SQL解析

源码地址&#xff1a;https://github.com/mybatis/mybatis-3/ 仓库地址&#xff1a;https://gitcode.net/qq_42665745/mybatis/-/tree/08-optimize-xml-parse 细化XML语句构建器&#xff0c;完善静态SQL解析 这一节主要是优化XML解析SQL部分&#xff0c;流程大概为&#xff…

【Java】解决Java报错:NumberFormatException

文章目录 引言1. 错误详解2. 常见的出错场景2.1 字符串包含非数字字符2.2 空字符串或 null 字符串2.3 数值超出范围 3. 解决方案3.1 验证字符串格式3.2 使用异常处理3.3 处理空字符串和 null 4. 预防措施4.1 数据验证4.2 编写防御性代码4.3 单元测试 结语 引言 在Java编程中&a…

认识Java中的String类

前言 大家好呀&#xff0c;本期将要带大家认识一下Java中的String类&#xff0c;本期注意带大家认识一些String类常用方法&#xff0c;和区分StringBuffer和StringBuilder感谢大家收看 一&#xff0c;String对象构造方法与原理 String类为我们提供了非常多的重载的构造方法让…

通过抑制治疗上调的环氧化酶-2来改善光动力性能的肿瘤归巢嵌合肽菱形体

引用信息 文 章&#xff1a;Tumor Homing Chimeric Peptide Rhomboids to Improve Photodynamic Performance by Inhibiting Therapy‐Upregulated Cyclooxygenase-2. 期 刊&#xff1a;Smal&#xff08;影响因子&#xff1a;13.3&#xff09; 发表时间&#xff1a…

Point-LIO:鲁棒高带宽激光惯性里程计

1. 动机 现有系统都是基于帧的&#xff0c;类似于VSLAM系统&#xff0c;频率固定&#xff08;例如10Hz)&#xff0c;但是实际上LiDAR是在不同时刻进行顺序采样&#xff0c;然后积累到一帧上&#xff0c;这不可避免地会引入运动畸变&#xff0c;从而影响建图和里程计精度。此外…