Springboot 验证码生成和校验,图片格式和base64编码串

private int lineSize = 30; //验证码中夹杂的干扰线数量

private int randomStrNum = 4; //验证码字符个数

private String randomString = “0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWSYZ”;

private final String sessionKey = “JCCODE”;

//字体的设置

private Font getFont() {

return new Font(“Times New Roman”, Font.ROMAN_BASELINE, 40);

}

//颜色的设置

private static Color getRandomColor(int fc, int bc) {

fc = Math.min(fc, 255);

bc = Math.min(bc, 255);

int r = fc + random.nextInt(bc - fc - 16);

int g = fc

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

  • random.nextInt(bc - fc - 14);

int b = fc + random.nextInt(bc - fc - 12);

return new Color(r, g, b);

}

//干扰线的绘制

private void drawLine(Graphics g) {

int x = random.nextInt(width);

int y = random.nextInt(height);

int xl = random.nextInt(20);

int yl = random.nextInt(10);

g.drawLine(x, y, x + xl, y + yl);

}

//随机字符的获取

private String getRandomString(int num){

num = num > 0 ? num : randomString.length();

return String.valueOf(randomString.charAt(random.nextInt(num)));

}

//字符串的绘制

private String drawString(Graphics g, String randomStr, int i) {

g.setFont(getFont());

g.setColor(getRandomColor(108, 190));

//System.out.println(random.nextInt(randomString.length()));

String rand = getRandomString(random.nextInt(randomString.length()));

randomStr += rand;

g.translate(random.nextInt(3), random.nextInt(6));

g.drawString(rand, 40 * i + 10, 25);

return randomStr;

}

//生成随机图片

public void getRandomCodeImage(HttpServletRequest request, HttpServletResponse response){

HttpSession session = request.getSession();

// BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);

Graphics g = image.getGraphics();

g.fillRect(0, 0, width, height);

g.setColor(getRandomColor(105, 189));

g.setFont(getFont());

// 干扰线

for (int i = 0; i < lineSize; i++) {

drawLine(g);

}

// 随机字符

String randomStr = “”;

for (int i = 0; i < randomStrNum; i++) {

randomStr = drawString(g, randomStr, i);

}

System.out.println(“随机字符:”+randomStr);

g.dispose();

//移除之前的session中的验证码信息

session.removeAttribute(sessionKey);

//重新将验证码放入session

session.setAttribute(sessionKey, randomStr);

try {

// 将图片以png格式返回,返回的是图片

ImageIO.write(image, “PNG”, response.getOutputStream());

} catch (Exception e) {

e.printStackTrace();

}

}

//生成随机图片的base64编码字符串

public String getRandomCodeBase64(HttpServletRequest request, HttpServletResponse response) {

HttpSession session = request.getSession();

// BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);

Graphics g = image.getGraphics();

g.fillRect(0, 0, width, height);

g.setColor(getRandomColor(105, 189));

g.setFont(getFont());

//干扰线

for (int i = 0; i < lineSize; i++) {

drawLine(g);

}

//随机字符

String randomStr = “”;

for (int i = 0; i < randomStrNum; i++) {

randomStr = drawString(g, randomStr, i);

}

System.out.println(“随机字符:”+randomStr);

g.dispose();

session.removeAttribute(sessionKey);

session.setAttribute(sessionKey, randomStr);

String base64String = “”;

try {

// 直接返回图片

// ImageIO.write(image, “PNG”, response.getOutputStream());

//返回 base64

ByteArrayOutputStream bos = new ByteArrayOutputStream();

ImageIO.write(image, “PNG”, bos);

byte[] bytes = bos.toByteArray();

Base64.Encoder encoder = Base64.getEncoder();

base64String = encoder.encodeToString(bytes);

} catch (Exception e) {

e.printStackTrace();

}

return base64String;

}

}

接下来写接口,创建一个ValidateCodeController.java,

先是生成验证码,返回图片的接口:

import com.example.demo.util.ValidateCodeUtil;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

/**

  • @Author : JCccc

  • @CreateTime : 2019/9/25

  • @Description :

**/

@RestController

public class ValidateCodeController {

//返回验证码图片

@GetMapping("/getCaptchaImg")

public void getCaptchaImg(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

try {

response.setContentType(“image/png”);

response.setHeader(“Cache-Control”, “no-cache”);

response.setHeader(“Expire”, “0”);

response.setHeader(“Pragma”, “no-cache”);

ValidateCodeUtil validateCode = new ValidateCodeUtil();

// getRandomCodeImage方法会直接将生成的验证码图片写入response

validateCode.getRandomCodeImage(request, response);

// System.out.println(“session里面存储的验证码为:”+session.getAttribute(“JCCODE”));

} catch (Exception e) {

e.printStackTrace();

}

}

}

用postman来调用下接口,

可以看到控制台的打印,这个验证码字符串已经存入了session(在后面的验证接口有介绍取值)

OK,接下来是编写一个校验验证码接口:

//验证码校验

@GetMapping("/checkCaptcha")

public boolean getCheckCaptcha(@RequestParam(“code”) String code, HttpSession session) {

try {

//toLowerCase() 不区分大小写进行验证码校验

String sessionCode= String.valueOf(session.getAttribute(“JCCODE”)).toLowerCase();

System.out.println(“session里的验证码:”+sessionCode);

String receivedCode=code.toLowerCase();

System.out.println(“用户的验证码:”+receivedCode);

return !sessionCode.equals("") && !receivedCode.equals("") && sessionCode.equals(receivedCode);

} catch (Exception e) {

return false;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值