SpringBoot登录验证码实现过程详解今天记录⼀下验证码的实现,希望能够帮助到⼤家!
⾸先我们看⼀下实现的效果:
此验证码的实现没有⽤到太多的插件,话不多说直接上代码,⼤家拿过去就可以⽤。
中间⽤到了org.apachemons.lang3.RandomUtils⼯具类,需要pom配置:
<!-- mvnrepository/artifact/org.apachemons/commons-lang3 -->
<dependency>
<groupId>org.apachemons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
1.验证码类
uyou.login.util.validatecode;
import lombok.Data;
/
**
* 验证码类
*/
public class VerifyCode {
private String code;
private byte[] imgBytes;
private long expireTime;
public String getCode() {
return code;
}
public void setCode(String code) {
}
public byte[] getImgBytes() {
return imgBytes;
}
public void setImgBytes(byte[] imgBytes) {
this.imgBytes = imgBytes;
}
public long getExpireTime() {
return expireTime;
}
public void setExpireTime(long expireTime) {
}
}
2.验证码⽣成接⼝
uyou.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.验证码⽣成实现类
uyou.login.util.validatecode;
uyou.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 = Logger(SimpleCharVerifyCodeGenImpl.class);
private static final String[] FONT_TYPES = { "u5b8bu4f53", "u65b0u5b8bu4f53", "u9ed1u4f53", "u6977u4f53", "u96b6u4e66" }; 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 = int(width);
int y = int(height);
int x1 = int(width);
int y1 = int(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 = Graphics();
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.ByteArray());
}
catch (IOException e) {
<(e.getMessage(), e);
verifyCode = null;
}
return verifyCode;
}
/**
* 设置字符颜⾊⼤⼩
*
* @param g
* @param randomStr
*/
private void createCharacter(Graphics g, String randomStr) {
char[] charArray = CharArray();
for (int i = 0; i < charArray.length; i++) {
//设置RGB颜⾊算法参数
g.setColor(new Color(50 + int(100),
+ int(100), 50 + int(100)));
/
/设置字体⼤⼩,类型
g.setFont(new Font(FONT_int(FONT_TYPES.length)], Font.BOLD, 26)); //设置x y 坐标
g.drawString(String.valueOf(charArray[i]), 15 * i + 5, 19 + int(8));
}
}
}
4.⼯具类
uyou.util;
import java.awt.*;
import java.util.Random;
public class RandomUtils extends org.apachemons.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_int(CODE_SEQ.length)]));
}
String();
}
public static String randomNumberString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.valueOf(NUMBER_int(NUMBER_ARRAY.length)]));
}
String();
}
public static Color randomColor(int fc, int bc) {
int f = fc;
int b = bc;
spring boot原理流程
Random random = new Random();
if (f > 255) {
f = 255;
}
if (b > 255) {
b = 255;
}
return new Color(f + int(b - f), f + int(b - f), f + int(b - f));
}
public static int nextint(int bound) {
int(bound);
}
}
经过以上代码,我们的验证码⽣成功能基本上已经实现了,现在还需要⼀个controller来调⽤它。@ApiOperation(value = "验证码")
@GetMapping("/verifyCode")
public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
try {
//设置长宽
VerifyCode verifyCode = ate(80, 28);
String code = Code();
LOGGER.info(code);
//将VerifyCode绑定session
//设置响应头
response.setHeader("Pragma", "no-cache");
//设置响应头
response.setHeader("Cache-Control", "no-cache");
//在代理服务器端防⽌缓冲
response.setDateHeader("Expires", 0);
//设置响应内容类型
response.setContentType("image/jpeg");
}
catch (IOException e) {
LOGGER.info("", e);
}
}
搞定!后台编写到此结束了。那么⼜会有博友说了:“说好的实现效果呢?”
好吧,那么我们继续前端的代码编写。
前端代码:
<html>
<body>
<div>
<input id="code" placeholder="验证码" type="text" class=""
>
<!-- 验证码显⽰ -->
<img οnclick="javascript:getvCode()" id="verifyimg" />
</div>
<script type="text/javascript">
getvCode();
/**
* 获取验证码
* 将验证码写到login.html页⾯的id = verifyimg 的地⽅
*/
function getvCode() {
}
//为url添加时间戳
function timestamp(url) {
var getTimestamp = new Date().getTime();
if (url.indexOf("?") > -1) {
url = url + "×tamp=" + getTimestamp
} else {
url = url + "?timestamp=" + getTimestamp
}
return url;
};
</script>
</body>
</html>
可以实现点击图⽚更换验证码。
实现效果:
当然⽂章开头的截图是我系统中的截图,需要⼤家⾃⼰去根据⾃⼰的情况去开发前端了。以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论