2、图形验证码

news2025/2/23 19:30:08

1、图形验证码设计

1.1思路

        现今,市面上的图形验证码付费的,免费的多种多样,主要形式有滑动拼图、文字点选、语序点选、字体识别、空间推理、智能随机等。

        而处理也分为web端和sever端两部分

        此处以免费的kaptcha 为例,进行数字图形验证码的解析

2、server 端

2.1 controller 

@RestController
@Slf4j
@RequestMapping("/sys")
public class SysLoginController {

    @Resource
    private ISysCaptchaService sysCaptchaService;

    @GetMapping("/captcha/{uuid}")
    public void captcha(HttpServletResponse response, @PathVariable("uuid") String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

}

2.2 service

public interface ISysCaptchaService extends IService<SysCaptcha> {
    /**
     * 获取图片验证码
     *
     * @param uuid uuid
     * @return Image
     */
    BufferedImage getCaptcha(String uuid);
}

2.3 serviceImpl

//此处引入了kaptcha的Producer
import com.google.code.kaptcha.Producer;

@Service
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaMapper, SysCaptcha> implements ISysCaptchaService {
    @Resource
    private Producer producer;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StrUtil.isBlank(uuid)) {
            throw new RuntimeException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        SysCaptcha captchaEntity = new SysCaptcha();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtil.offset(DateUtil.date(), DateField.MINUTE, 5).toLocalDateTime());
        //将数据写入数据库,此处最好可以写入到redis等缓存中,不需要过期手动处理
        this.save(captchaEntity);

        return producer.createImage(code);
    }
}

2.4 配置KaptchaConfig

@Configuration
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.space", "5");
        properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

不进行config配置时,会报如下异常

**************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean of type 'com.google.code.kaptcha.Producer' that could not be found.

Action:
Consider defining a bean of type 'com.google.code.kaptcha.Producer' in your configuration.

2.5 pom.xml

    <properties>
        <kaptcha.version>2.3.5</kaptcha.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.youkol.support.kaptcha</groupId>
            <artifactId>kaptcha-spring-boot-starter</artifactId>
            <version>${kaptcha.version}</version>
        </dependency>
    </dependencies>

2.6 数据库表

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for sys_captcha
-- ----------------------------
DROP TABLE IF EXISTS `sys_captcha`;
CREATE TABLE `sys_captcha`  (
  `uuid` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'uuid',
  `code` varchar(6) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '验证码',
  `expire_time` datetime NULL DEFAULT NULL COMMENT '过期时间',
  PRIMARY KEY (`uuid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '系统验证码' ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

2.7 测试

3、web端

3.1 vue3 安装 uuid 小插件

3.1.1 安装

pnpm add vue3-uuid

如果pnpm安装异常

切换pnpm源

pnpm config set registry https://registry.npmmirror.com //切换淘宝源 

3.1.2 main.ts中引入

import { createApp } from 'vue'

import App from './App.vue'
import router from './router'
import pinia from '@/stores'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
//@ts-expect-error忽略当前文件ts类型的检测否则有红色提示(打包会失败)
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import 'virtual:svg-icons-register'
import '@/styles/index.scss'
//使用UUID
import UUID from 'vue3-uuid'

const app = createApp(App)

app.use(pinia)
app.use(router)
app.use(UUID)
app.use(ElementPlus, {
  'locale': zhCn
})

app.mount('#app')

3.1.3 使用

import { uuid } from 'vue3-uuid'

const getCaptcha = () => {
  const id = uuid.v4()
  console.log('@@@@', id)
}

3.2 加载验证码

3.2.1 Template

<template>
  <div class="container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          class="login_form"
          :model="userStore.user"
          :rules="loginRules"
          ref="loginForm"
        >
          <h1>欢迎登录{{ setting.title }}</h1>
          <el-form-item>
            <el-input
              v-model="userStore.user.username"
              placeholder="请输入用户名"
              prefix-icon="User"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="userStore.user.password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
            ></el-input>
          </el-form-item>
          <div class="captcha">
            <el-form-item>
              <el-input type="text" placeholder="请输入验证码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-image :src="captchaUrl" @click="getCaptcha" style="width: 150px;height: 30px"></el-image>
              <el-button style="width: 150px;" @click="refresh">刷新</el-button>
            </el-form-item>
          </div>
          <div class="class-btn">
            <el-button type="primary" @click="login">登录</el-button>
            <el-button type="primary" @click="register">注册</el-button>
          </div>

        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

3.2.2 script

<script setup lang="ts">
import { uuid } from 'vue3-uuid'

let captchaUrl = ref('')
const getCaptcha = async () => {
  const id = uuid.v4()
  console.log(id)
  captchaUrl.value = import.meta.env.VITE_SERVER + '/sys/captcha/' + id
}
const refresh = () => {
  getCaptcha()
}

onMounted(() => {
  getCaptcha()
})

</script>

3.2.3 加载结果

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

分支与循环(二)

目录 1.switch语句 1)switch语法形式 2&#xff09;if语句和switch语句的对比 3) switch语句中的break 4) switch语句中的default 5) switch语句中的case和default的顺序问题 2.while循环 1) if 和 while的对比 2) while语句的执行流程​编辑 3&#xff09;while循环的…

linux 基础命令、gcc的基础用法

1、ls——>列出目录下的内容 语法&#xff1a;ls [-a -l -h] [Linux路径] &#xff08;1&#xff09;-a -l -h 是可选的选项 &#xff08;2&#xff09;Linux路径是此命令的可选参数 ①当不使用选项和参数&#xff0c;直接使用 ls 命令本体&#xff0c;表示&#xff1a;…

图论·Day01

P3371 P4779 P3371 【模板】单源最短路径&#xff08;弱化版&#xff09; 注意的点&#xff1a; 边有重复&#xff0c;选择最小边&#xff01;对于SPFA算法容易出现重大BUG&#xff0c;没有负权值的边时不要使用&#xff01;&#xff01;&#xff01; 70分代码 朴素板dijsk…

【Web】

1、配仓库 [rootlocalhost yum.repos.d]# vi rpm.repo ##本地仓库标准写法 [baseos] namemiaoshubaseos baseurl/mnt/BaseOS gpgcheck0 [appstream] namemiaoshuappstream baseurlfile:///mnt/AppStream gpgcheck0 2、挂载 [rootlocalhost ~]mount /dev/sr0 /mnt mount: /m…

类与对像(1)

好几个月没有写了&#xff0c;差了好多&#xff0c;这些天补回来吧。 接下来&#xff0c;让我们正式步入C与C语言开始不同的地方。 我对类的理解&#xff1a;类是对于具有相同或相似属性的数据集合。 类的关键词&#xff1a;class&#xff0c;public&#xff0c;protected&a…

vue3中pinia使用持久化管理

安装插件 npm install pinia pinia-plugin-persistpinia进行注册 创建index.ts import { createPinia } from pinia; //对外暴露大仓库 export default createPinia(); 在mian.ts //引入pinpa import { createApp } from vue //引入根组件 import App from ./App.vue const…

昇思MindSpore学习入门-评价指标

当训练任务结束&#xff0c;常常需要评价函数&#xff08;Metrics&#xff09;来评估模型的好坏。不同的训练任务往往需要不同的Metrics函数。例如&#xff0c;对于二分类问题&#xff0c;常用的评价指标有precision&#xff08;准确率&#xff09;、recall&#xff08;召回率&…

全网最详细的appium 自动化测试iOS(二)

一、环境准备&#xff1a; 1、安装appium 2、xcode (appium 版本&#xff1a;12.1.0 xcode版本&#xff1a;12.5 可正常运行&#xff0c;ps:appium 版本&#xff1a;12.1.0 xcode版本&#xff1a;13.0 一直报奇奇怪怪的错误&#xff09; 3、依赖工具包安装 brew install…

基于星火大模型的群聊对话分角色要素提取挑战赛

赛事任务与数据 2024 iFLYTEK A.I.开发者大赛-讯飞开放平台 (xfyun.cn) 从给定的<客服>与<客户>的群聊对话中, 提取出指定的字段信息&#xff0c;待提取的全部字段见下数据说明。 赛题方提供了184条真实场景的群聊对话数据以及人工标注后的字段提取结果&#xf…

linux centos 安装niginx并且添加ssl(https)模块

文章目录 前言一、nginx安装教程1.流程步骤 总结 前言 一、nginx安装教程 1.流程步骤 代码如下&#xff08;示例&#xff09;&#xff1a; 1.先下载linux安装包 2.解压安装命令 sudo tar -zxvf nginx-1.20.1.tar.gz3.进入解压后的目录 sudo cd nginx-1.20.14.安装 sudo y…

opencv环境搭建-python

最近遇到了一些图像处理的需求&#xff0c;所以需要学习一下opencv,来记录一下我的学习历程。 安装numpy pip install -i https://pypi.tuna.tsinghua.edu.cn/simple numpy安装matplotlib pip install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib安装opencv …

CSS技巧:用CSS绘制超写实的酷炫徽章缎带效果,超漂亮,超酷炫

为什么要用CSS来画个徽章&#xff1f;这货脑子进水了吧&#xff01; 今天在电脑前设计&#xff0c;要做徽章效果。突然觉得可以尝试用css实现近似的效果。说干就干&#xff0c;打开编辑器&#xff0c;让我的手指头活跃起来&#xff01; 技术要点 通过多个圆形嵌套和渐变属性…

Google Earth Engine(GEE)——在控制台打印出来所选区域的缩略图

结果 函数 ui.Thumbnail(image, params, onClick, style) A fixed-size thumbnail image generated asynchronously from an ee.Image. Arguments: image (Image, optional): The ee.Image from which to generate the thumbnail. Defaults to an empty ee.Image. param…

MySQL 集群

MySQL 集群有多种类型&#xff0c;每种类型都有其特定的用途和优势。以下是一些常见的 MySQL 集群解决方案&#xff1a; 1. MySQL Replication 描述&#xff1a;MySQL 复制是一种异步复制机制&#xff0c;允许将一个 MySQL 数据库的数据复制到一个或多个从服务器。 用途&…

优化LabVIEW代码以提高软件性能

优化LabVIEW代码对于提高软件性能、减少执行时间和资源消耗至关重要。以下是一些具体的策略和方法&#xff0c;可以帮助LabVIEW程序员优化代码&#xff1a; 1. 代码结构和模块化 使用子VI&#xff1a;将重复使用的代码段封装成子VI&#xff0c;提高代码的可读性和可维护性。 避…

星光云VR全景系统源码

星光云VR全景系统源码 体验地址请查看

11 docker安装redis

目录 安装redis 1. 配置redis配置文件redis.conf 1.1. 找到redis.conf文件 1.2. 配置文件 2. 启动容器 3. 测试redis-cli连接 4. 证明docker使用的是指定的配置文件 安装redis 1. 配置redis配置文件redis.conf 1.1. 找到redis.conf文件 宿主机创建目录/app/redis在/a…

vb.netcad二开自学笔记1:万里长征第一步Hello CAD!

已入门的朋友请绕行&#xff01; 今天开启自学vb.net 开发autocad&#xff0c;网上相关资料太少了、太老了。花钱买课吧&#xff0c;穷&#xff01;又舍不得&#xff0c;咬牙从小白开始摸索自学吧&#xff0c;虽然注定是踏上了一条艰苦之路&#xff0c;顺便作个自学笔记备忘!积…

[AI Perplexica] 安装指南:轻松部署AI驱动的开源搜索引擎

[AI Perplexica] AI驱动的开源搜索引擎[AI Perplexica] 深入解析&#xff0c;AI 架构揭秘 之前&#xff0c;我们看过了 Perplexica 的介绍&#xff0c;特点和架构&#xff0c;了解了其工作原理。 今天&#xff0c;我们一起来部署下 安装 docker 安装 docker https://docs.…

2024年江苏省研究生数学建模竞赛B题火箭烟幕弹运用策略优化论文和代码分析

经过不懈的努力&#xff0c; 2024年江苏省研究生数学建模竞赛B题火箭烟幕弹运用策略优化论文和代码已完成&#xff0c;代码为B题全部问题的代码&#xff0c;论文包括摘要、问题重述、问题分析、模型假设、符号说明、模型的建立和求解&#xff08;问题1模型的建立和求解、问题2模…