最近有个需求,需要返回验证码,以前我一直以为有验证码是在前端做的,后面才发现,前端存储的只是一个图片,和一个 sessionid 数据,用户根据图片输入内容,前端取出 sessionid 的再把用户输入的一起传到后端,后端进行校验,这就是最常见的验证码逻辑。
这里直接创建一个简单的 springboot 工程。
只要有 spring web 模块即可
主要工程结构
com.example.verificationcode.VerificationcodeApplication
package com.example.verificationcode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class VerificationcodeApplication {
public static void main(String[] args) {
SpringApplication.run(VerificationcodeApplication.class, args);
}
}
com.example.verificationcode.VerificationCodeController
package com.example.verificationcode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
@Controller
public class VerificationCodeController {
/**
* 二维码接口
* @param request
* @param response
*/
/* 获取验证码图片*/
@RequestMapping("/getVerifyCode")
public void getVerificationCode(HttpServletResponse response,HttpServletRequest request) {
try {
int width=200;
int height=69;
BufferedImage verifyImg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//生成对应宽高的初始图片
String randomText = VerifyCode.drawRandomText(width,height,verifyImg);
//单独的一个类方法,出于代码复用考虑,进行了封装。
//功能是生成验证码字符并加上噪点,干扰线,返回值为验证码字符
request.getSession().setAttribute("verifyCode", randomText);
response.setContentType("image/png");//必须设置响应内容类型为图片,否则前台不识别
OutputStream os = response.getOutputStream(); //获取文件输出流
ImageIO.write(verifyImg,"png",os);//输出图片流
os.flush();
os.close();//关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
}
com.example.verificationcode.VerifyCode
package com.example.verificationcode;
/*对图片进行处理的类和方法*/
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public class VerifyCode {
public static String drawRandomText(int width, int height, BufferedImage verifyImg) {
Graphics2D graphics = (Graphics2D)verifyImg.getGraphics();
graphics.setColor(Color.WHITE);//设置画笔颜色-验证码背景色
graphics.fillRect(0, 0, width, height);//填充背景
graphics.setFont(new Font("微软雅黑", Font.BOLD, 40));
//数字和字母的组合
String baseNumLetter= "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
StringBuffer sBuffer = new StringBuffer();
int x = 10; //旋转原点的 x 坐标
String ch = "";
Random random = new Random();
for(int i = 0;i < 4;i++){
graphics.setColor(getRandomColor());
//设置字体旋转角度
int degree = random.nextInt() % 45; //角度小于30度
int dot = random.nextInt(baseNumLetter.length());
ch = baseNumLetter.charAt(dot) + "";
sBuffer.append(ch);
//正向旋转
graphics.rotate(degree * Math.PI / 180, x, 45);
graphics.drawString(ch, x, 45);
//反向旋转,不反向旋转的话字符会跑出画布
graphics.rotate(-degree * Math.PI / 180, x, 45);
x += 48;
}
//画干扰线
for (int i = 0; i <6; i++) {
// 设置随机颜色
graphics.setColor(getRandomColor());
// 随机画线
graphics.drawLine(random.nextInt(width), random.nextInt(height),
random.nextInt(width), random.nextInt(height));
}
//添加噪点
for(int i=0;i<30;i++){
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
graphics.setColor(getRandomColor());
graphics.fillRect(x1, y1, 2,2);
}
return sBuffer.toString();
}
/**
* 随机取色
*/
private static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256),
ran.nextInt(256), ran.nextInt(256));
return color;
}
}
测试结果
如果注释掉
将会出现该情况
源码地址:https://github.com/weijieqiu/iStudy