springboot + jq 随机生成图片验证码
效果如下
1.前端 html
2.前端 js
$(function(){
//首次获取验证码
$("#random_pic").attr("src","/util/getVerify.html?"+Math.random());
});
function getVerify(obj){
//点击获取验证码
obj.src = "/util/getVerify.html?"+Math.random();
}
3.后台 生成随机验证码图片
1)图片名是picName, 保存在session里, 供校验使用
2)图片本身是img, 写入输出流, 给前端显示 (图片保存在内存中)
package com.prj.utils;
import com.prj.commons.Constants;
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
* Created by Alwen
* 2018/11/13 15:02
*/
@Slf4j
//生成随机验证码
public class RandomPic {
private static Random random = new Random();
private static int width = 120;
private static int height = 50;
private static String str = "abcdefghjkmnpqrstuvwxyz23456789"; //允许在图片内显示的字符
private static int randomNum(int min, int max) {
int num = 0;
num = random.nextInt(max - min) + min;
return num;
}
//设置颜色
private static Color setColor(int min, int max) {
int r = min + random.nextInt(max - min);
int g = min + random.nextInt(max - min);
int b = min + random.nextInt(max - min);
return new Color(r, g, b);
}
public static void getPic(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//在内存中创建图片
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//在图片上画一个矩形当背景
Graphics g = img.getGraphics();
g.setColor(setColor(150, 230));
g.fillRect(0, 0, width, height);
//生成的字符串
String picName = "";
for (int i = 0; i < 4; i++) {
g.setColor(setColor(30, 140));
g.setFont(new Font("黑体", Font.PLAIN, 40));
char c = str.charAt(randomNum(0, str.length()));
g.drawString(String.valueOf(c), 10 + i * 30, randomNum(height - 30, height));
picName += c;
}
//画随机线
for (int i = 0; i < 25; i++) {
g.setColor(setColor(50, 180));
g.drawLine(randomNum(0, width), randomNum(0, height), randomNum(0, width), randomNum(0, height));
}
//把内存中创建的图像输出到文件中
// File file = new File("C:/Users/AlwenZwei/Desktop/mk_file/vcode.png");
// ImageIO.write(img, "png", file);
//把图片创建在内存中
ImageIO.write(img, "JPEG", response.getOutputStream());
log.info("图片: " + picName);
HttpSession session = request.getSession();
session.setAttribute(Constants.RANDOM_PIC, picName);
}
}
4.前端getVerify调用方法, 获取随机图片
@RequestMapping("/getVerify.html")
public void getVerify(HttpServletRequest request, HttpServletResponse response) {
//设置相应信息
response.setContentType("image/jpeg");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
try {
//输出图片
RandomPic.getPic(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
至此, 图片已经输出到img标签, 图片的内容保存在session中, 通过ajax可以进行校验