后端返回验证码图片与验证机制实现
后端返回验证码图片与验证机制实现
验证码是一种防止恶意请求的机制,常用于注册、登录等功能中。我们可以通过后端动态生成图片验证码并在前端展示,用户输入后由后端校验。
一、生成验证码图片
使用 Java 中的 BufferedImage 绘图:
public class CaptchaUtil {
public static String generateCode(int length) {
String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
Random rand = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(chars.charAt(rand.nextInt(chars.length())));
}
return sb.toString();
}
public static BufferedImage createImage(String code) {
int width = 120, height = 40;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 28));
g.drawString(code, 20, 30);
g.dispose();
return image;
}
}
二、验证码接口返回图片
@GetMapping("/captcha")
public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
String code = CaptchaUtil.generateCode(5);
session.setAttribute("captcha", code);
BufferedImage image = CaptchaUtil.createImage(code);
response.setContentType("image/png");
ImageIO.write(image, "png", response.getOutputStream());
}
三、前端展示验证码
<img id="captchaImg" src="/captcha" onclick="this.src='/captcha?'+Math.random()">
四、提交校验接口
@PostMapping("/verify")
public String verify(@RequestParam String input, HttpSession session) {
String correct = (String) session.getAttribute("captcha");
if (correct != null && correct.equalsIgnoreCase(input)) {
return "验证码正确";
} else {
return "验证码错误";
}
}
五、总结
验证码图片是阻止机器人脚本攻击的重要手段。配合 Session 或 Redis,可以实现有效校验和安全防护。

浙公网安备 33010602011771号