验证码功能只需复制粘贴即可,做个记录方便回看
1. 绘制验证码
public class VerifyCode {
private int width = 100;
private int height = 50;
private int CODE_COUNT = 4;
private int LINE_COUNT = 5;
private String[] FONTNAMES = {"宋体", "楷体", "隶书", "微软雅黑"};
private String CODES = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private Random random = new Random();
private String code;
// 随机RGB,RGB不易过高
private Color randomColor() {
int red = random.nextInt(150);
int green = random.nextInt(150);
int blue = random.nextInt(150);
return new Color(red, green, blue);
}
// 随机字体
private Font randomFont() {
String name = FONTNAMES[random.nextInt(FONTNAMES.length)];
int style = random.nextInt(4);
int size = random.nextInt(5) + 25;
return new Font(name, style, size);
}
// 随机字符
private char randomChar() {
return CODES.charAt(random.nextInt(CODES.length()));
}
// 返回绘制的验证码图片
public BufferedImage getImage() {
// 绘制背景
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.setColor(new Color(250, 250, 250));
g2.fillRect(0, 0, width, height);
// 绘制验证码
StringBuffer sb = new StringBuffer();
for (int i = 0; i < CODE_COUNT; i++) {
String s = randomChar() + "";
sb.append(s);
g2.setColor(randomColor());
g2.setFont(randomFont());
float x = i * width / CODE_COUNT;
float y = height / 2 + random.nextInt(height / 4);
g2.drawString(s, x, y);
}
// 绘制干扰线
for (int i = 0; i < LINE_COUNT; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
g2.setColor(randomColor());
g2.setStroke(new BasicStroke(1));
g2.drawLine(x1, y1, x2, y2);
}
this.code = sb.toString();
return image;
}
// 获取验证码
public String getCode() {
return code;
}
// 输出图片
public static void output(BufferedImage image, OutputStream out) throws IOException {
ImageIO.write(image, "JPEG", out);
}
}
2. Controller层
@RestController
public class VerifyCodeController {
@GetMapping("/verifyCode")
public void verifyCode(HttpServletRequest req, HttpServletResponse res) throws IOException {
VerifyCode vc = new VerifyCode();
BufferedImage image = vc.getImage();
String code = vc.getCode();
HttpSession session = req.getSession();
session.setAttribute("verifyCode", code);
VerifyCode.output(image, res.getOutputStream());
}
}
3. 页面
<img src="/verifyCode" alt="看不清楚,点击换一张">