此验证码的实现没有用到太多的插件,话不多说直接上代码,大家拿过去就可以用。

1.验证码类

package com.youyou.login.util.validatecode;

import lombok.Data;

/**
* 验证码类
*/
@Data
public class VerifyCode { private String code; private byte[] imgBytes; private long expireTime; }

2.验证码生成接口

package com.youyou.login.util.validatecode;

import java.io.IOException;
import java.io.OutputStream; /**
* 验证码生成接口
*/
public interface IVerifyCodeGen { /**
* 生成验证码并返回code,将图片写的os中
*
* @param width
* @param height
* @param os
* @return
* @throws IOException
*/
String generate(int width, int height, OutputStream os) throws IOException; /**
* 生成验证码对象
*
* @param width
* @param height
* @return
* @throws IOException
*/
VerifyCode generate(int width, int height) throws IOException;
}

3.验证码生成实现类

package com.youyou.login.util.validatecode;

import com.youyou.util.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random; /**
* 验证码实现类
*/
public class SimpleCharVerifyCodeGenImpl implements IVerifyCodeGen { private static final Logger logger = LoggerFactory.getLogger(SimpleCharVerifyCodeGenImpl.class); private static final String[] FONT_TYPES = { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" }; private static final int VALICATE_CODE_LENGTH = 4; /**
* 设置背景颜色及大小,干扰线
*
* @param graphics
* @param width
* @param height
*/
private static void fillBackground(Graphics graphics, int width, int height) {
// 填充背景
graphics.setColor(Color.WHITE);
//设置矩形坐标x y 为0
graphics.fillRect(0, 0, width, height); // 加入干扰线条
for (int i = 0; i < 8; i++) {
//设置随机颜色算法参数
graphics.setColor(RandomUtils.randomColor(40, 150));
Random random = new Random();
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
graphics.drawLine(x, y, x1, y1);
}
} /**
* 生成随机字符
*
* @param width
* @param height
* @param os
* @return
* @throws IOException
*/
@Override
public String generate(int width, int height, OutputStream os) throws IOException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
fillBackground(graphics, width, height);
String randomStr = RandomUtils.randomString(VALICATE_CODE_LENGTH);
createCharacter(graphics, randomStr);
graphics.dispose();
//设置JPEG格式
ImageIO.write(image, "JPEG", os);
return randomStr;
} /**
* 验证码生成
*
* @param width
* @param height
* @return
*/
@Override
public VerifyCode generate(int width, int height) {
VerifyCode verifyCode = null;
try (
//将流的初始化放到这里就不需要手动关闭流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
) {
String code = generate(width, height, baos);
verifyCode = new VerifyCode();
verifyCode.setCode(code);
verifyCode.setImgBytes(baos.toByteArray());
} catch (IOException e) {
logger.error(e.getMessage(), e);
verifyCode = null;
}
return verifyCode;
} /**
* 设置字符颜色大小
*
* @param g
* @param randomStr
*/
private void createCharacter(Graphics g, String randomStr) {
char[] charArray = randomStr.toCharArray();
for (int i = 0; i < charArray.length; i++) {
//设置RGB颜色算法参数
g.setColor(new Color(50 + RandomUtils.nextInt(100),
50 + RandomUtils.nextInt(100), 50 + RandomUtils.nextInt(100)));
//设置字体大小,类型
g.setFont(new Font(FONT_TYPES[RandomUtils.nextInt(FONT_TYPES.length)], Font.BOLD, 26));
//设置x y 坐标
g.drawString(String.valueOf(charArray[i]), 15 * i + 5, 19 + RandomUtils.nextInt(8));
}
}
}

4.工具类

package com.youyou.util;

import java.awt.*;
import java.util.Random; public class RandomUtils extends org.apache.commons.lang3.RandomUtils { private static final char[] CODE_SEQ = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' }; private static final char[] NUMBER_ARRAY = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; private static Random random = new Random(); public static String randomString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.valueOf(CODE_SEQ[random.nextInt(CODE_SEQ.length)]));
}
return sb.toString();
} public static String randomNumberString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.valueOf(NUMBER_ARRAY[random.nextInt(NUMBER_ARRAY.length)]));
}
return sb.toString();
} public static Color randomColor(int fc, int bc) {
int f = fc;
int b = bc;
Random random = new Random();
if (f > 255) {
f = 255;
}
if (b > 255) {
b = 255;
}
return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f), f + random.nextInt(b - f));
} public static int nextInt(int bound) {
return random.nextInt(bound);
}
}

经过以上代码,我们的验证码生成功能基本上已经实现了,现在还需要一个controller来调用它。

    @ApiOperation(value = "验证码")
@GetMapping("/verifyCode")
public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
try {
//设置长宽
VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
String code = verifyCode.getCode();
LOGGER.info(code);
//将VerifyCode绑定session
request.getSession().setAttribute("VerifyCode", code);
//设置响应头
response.setHeader("Pragma", "no-cache");
//设置响应头
response.setHeader("Cache-Control", "no-cache");
//在代理服务器端防止缓冲
response.setDateHeader("Expires", 0);
//设置响应内容类型
response.setContentType("image/jpeg");
response.getOutputStream().write(verifyCode.getImgBytes());
response.getOutputStream().flush();
} catch (IOException e) {
LOGGER.info("", e);
}
}

搞定!后台编写到此结束了。那么又会有博友说了:“说好的实现效果呢?”

好吧,那么我们继续前端的代码编写。

前端代码:

<html>
<body> <div>
<input id="code" placeholder="验证码" type="text" class=""
style="width:170px">
<!-- 验证码 显示 -->
<img οnclick="javascript:getvCode()" id="verifyimg" style="margin-left: 20px;"/>
</div> <script type="text/javascript">
getvCode(); /**
* 获取验证码
* 将验证码写到login.html页面的id = verifyimg 的地方
*/
function getvCode() {
document.getElementById("verifyimg").src = timestamp("http://127.0.0.1:81/verifyCode");
}
//为url添加时间戳
function timestamp(url) {
var getTimestamp = new Date().getTime();
if (url.indexOf("?") > -1) {
url = url + "&timestamp=" + getTimestamp
} else {
url = url + "?timestamp=" + getTimestamp
}
return url;
}; </script>
</body> </html>

可以实现点击图片更换验证码。

实现效果:

SpringBoot之后端图形验证码实现的更多相关文章

  1. 笔记——Springboot response、ServletOutputStream、图形验证码显示慢

    今天遇到一个图形验证码加载很慢的问题,大概耗时有200~500毫秒左右. 根据追踪,图形验证码图片生成耗时0~1毫秒,而response.getOutputStream.write()将图片写入前台页 ...

  2. Tornado框架实现图形验证码功能

    图形验证码是项目开发过程中经常遇到的一个功能,在很多语言中都有对应的不同形式的图形验证码功能的封装,python 中同样也有类似的封装操作,通过绘制生成一个指定的图形数据,让前端HTML页面通过链接获 ...

  3. vue项目经验:图形验证码接口get请求处理

    一般图形验证码处理: 直接把img标签的src指向这个接口,然后在img上绑定点击事件,点击的时候更改src的地址(在原来的接口地址后面加上随机数即可,避免缓存) <img :src=" ...

  4. JQ-用户注册用到的图形验证码,短信验证码点击事件,切换active类

    // 点击切换图形验证码 页面加载完后执行,类似window.onload $(function () { var imgCaptcha = $(".img-captcha"); ...

  5. springmvc的文件上传和JWT图形验证码

    相关pom依赖 <dependency> <groupId>commons-fileupload</groupId> <artifactId>commo ...

  6. 程序员不装x能行?先给登录来一个图形验证码!(canvas实现)

    细心的同学可以发现,现在很多网站当登录多次之后就会出现一个图形验证码,或是当提交表单.或点击获取手机验证码等等场景都会有图形验证码的出现. 那么图形验证码是为了解决什么问题而出现的呢? 什么是图形验证 ...

  7. SpringCloud SpringBoot 前后端分离企业级微服务架构源码赠送

    基于SpringBoot2.x.SpringCloud和SpringCloudAlibaba并采用前后端分离的企业级微服务敏捷开发系统架构.并引入组件化的思想实现高内聚低耦合,项目代码简洁注释丰富上手 ...

  8. 【web 安全测试思路】图形验证码对服务器的影响

    前言 图片验证码是为了防止恶意破解密码.刷票.论坛灌水等才出现的,但是你有没有想过,你的图形验证码竟然可能导致服务器的崩溃? 利用过程 这里以phpcms为例,首先需要找一个图形验证码. 将图片拖动到 ...

  9. vue 项目,获取手机验证码和图形验证码(iviewUI框架)

    1.编辑获取验证码模块 <Form ref="phoneFormItem" :model="phoneFormItem" :label-width=&qu ...

  10. WEB安全新玩法 [6] 防范图形验证码重复使用

    在完成关键业务操作时,要求用户输入图形验证码是防范自动化攻击的一种措施.为安全起见,即使针对同一用户,在重新输入信息时也应该更新图形验证码.iFlow 业务安全加固平台可以加强这方面的处理. 某网站系 ...

随机推荐

  1. NOI2024 集合 题解

    给个链接:集合. 很神秘的题目.基本上看到之后就可以想到哈希. 首先想到一个比较神秘的暴力.就是对于每个询问,扫一遍所有 \(a\) 中的数出现的位置,把它弄成一个哈希值(具体怎么弄随意)存到 set ...

  2. Windows下cmd中cd命令不起作用的原因和解决办法

    Windows下cmd中cd命令不起作用的原因和解决办法 如图:cd命令无效 原因:windows系统cmd换目录跨磁盘的话需要先进行磁盘的转换

  3. 【Appium】之自动化定位总结

    一.同级定位时,先定位上级 我想定位[必填]框,我先定位[姓名]的同一个上级 self.driver.find_element(MobileBy.XPATH,"//*[contains(@t ...

  4. 使用go+gin编写日志中间,实现自动化收集http访问信息,错误信息等,自动化生成日志文件

    1.首先在logger包下 点击查看代码 package logger import ( "fmt" "io" "net/http" &qu ...

  5. 呵,老板不过如此,SQL还是得看我

    2018年7月,大三暑假进行时,时间过得飞快,我到这边实习都已经一个月了. 我在没工作之前,我老是觉得生产项目的代码跟我平时自学练的会有很大的区别. 以为生产项目代码啥的都会规范很多,比如在接口上会做 ...

  6. sicp每日一题[1.43]

    Exercise 1.43 If f is a numerical function and n is a positive integer, then we can form the nth rep ...

  7. .NET 8 微软免费开源的 Blazor UI 组件库

    前言 .NET 8 的发布,微软推出了官方免费且开源的 Blazor UI 组件库 -- Fluent UI Blazor. 组件库提供了Web应用程序所需的工具,确保应用程序能够与 Microsof ...

  8. 使用gin实现简单的注册和登录功能

    一.前言 使用了gorm操作数据库,后端基于gin框架,只是一个简单的注册和登录与数据库交互的后端实现例子. 二.目录结构 -templates --regist.html --login.html ...

  9. 十种SQL的语法

    一.ORDER BY FIELD()自定义排序逻辑 ORDER BY FIELD(str,str1,...) 自定义排序sql如下: SELECT * from order_diy ORDER BY ...

  10. SQL Server的Descending Indexes降序索引

    SQL Server的Descending Indexes降序索引 背景索引是关系型数据库中优化查询性能的重要手段之一.对于需要处理大量数据的场景,合理的索引策略能够显著减少查询时间. 特别是在涉及多 ...