手写一个获取验证码的接口,超级简单
手写一个获取验证码的接口,超级简单,觉得有用就试试吧,话不多说代码附上
private static final int VERIFY_CODE_HEIGHT = 25; //验证码高度
private static final int VERIFY_CODE_WIDTH = 70; //验证码宽度
private static final char[] codeSequence = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
/**
* 获取验证码
* @param req 请求
* @param res 响应
* @throws IOException
*/
@GetMapping("verificationCode")
public void verificationCode(HttpServletRequest req, HttpServletResponse res) throws IOException {
BufferedImage image = new BufferedImage(VERIFY_CODE_WIDTH, VERIFY_CODE_HEIGHT,BufferedImage.TYPE_INT_RGB);
//获取图片上下文
Graphics graphics = image.getGraphics();
//生成随机类
Random random = new Random();
//设置背景色
graphics.setColor(getRandColor(200, 250));
graphics.fillRect(0, 0, VERIFY_CODE_WIDTH, VERIFY_CODE_HEIGHT);
// 设定字体
graphics.setFont(new Font("Times New Roman", Font.PLAIN, 18));
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
graphics.setColor(getRandColor(160, 200));
for (int i = 0; i < 160; i++) {
int x = random.nextInt(VERIFY_CODE_WIDTH);
int y = random.nextInt(VERIFY_CODE_HEIGHT);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
graphics.drawLine(x, y, x + xl, y + yl);
}
// 取随机产生的认证码(4位数字)
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(codeSequence[random.nextInt(10)]);
sRand += rand;
// 将认证码显示到图象中
graphics.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
graphics.drawString(rand, 13 * i + 10, 20);
}
// 图象生效
graphics.dispose();
// 输出图象到页面
//将VerifyCode绑定session(VerifyCode 可根据实际情况自行定义)
req.getSession().setAttribute("VerifyCode", sRand);
//设置响应头
res.setHeader("Pragma", "no-cache");
//设置响应头
res.setHeader("Cache-Control", "no-cache");
//在代理服务器端防止缓冲
res.setDateHeader("Expires", 0);
//设置响应内容类型
res.setContentType("image/jpeg");
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "JPEG", out);
res.setContentLength(out.size());
res.getOutputStream().write(out.toByteArray());
res.getOutputStream().flush();
}
设置背景色
/**
* 设置背景色
* @param i
* @param j
* @return
*/
private static Color getRandColor(int i, int j) {
Random random = new Random();
if (i > 255)
i = 255;
if (j > 255)
j = 255;
int r = i + random.nextInt(j - i);
int g = i + random.nextInt(j - i);
int b = i + random.nextInt(j - i);
return new Color(r, g, b);
}
Postman请求返回示例
下一篇:
java获取客户端的IP地址工具类
