如何开发java验证码
生成随机验证码
使用Java的Random类或SecureRandom生成随机字符或数字组合。通常验证码包含数字、大小写字母,长度为4-6位。
import java.util.Random;
public class CaptchaGenerator {
private static final String CHAR_LIST = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final int LENGTH = 6;
public static String generateCaptcha() {
Random random = new Random();
StringBuilder captcha = new StringBuilder();
for (int i = 0; i < LENGTH; i++) {
int index = random.nextInt(CHAR_LIST.length());
captcha.append(CHAR_LIST.charAt(index));
}
return captcha.toString();
}
}
生成图形验证码
使用Java的BufferedImage绘制验证码图片,添加干扰线、噪点等增强安全性。
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class CaptchaImageGenerator {
public static byte[] generateImage(String captchaText) throws IOException {
int width = 200, height = 50;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
// 背景色
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
// 验证码文字
graphics.setColor(Color.BLACK);
graphics.setFont(new Font("Arial", Font.BOLD, 30));
graphics.drawString(captchaText, 50, 35);
// 干扰线
graphics.setColor(Color.GRAY);
for (int i = 0; i < 5; i++) {
int x1 = (int) (Math.random() * width);
int y1 = (int) (Math.random() * height);
int x2 = (int) (Math.random() * width);
int y2 = (int) (Math.random() * height);
graphics.drawLine(x1, y1, x2, y2);
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(image, "png", output);
return output.toByteArray();
}
}
验证码存储与校验
将生成的验证码存储在服务端(如Session或Redis),用户提交时进行比对。
import javax.servlet.http.HttpSession;
public class CaptchaValidator {
public static boolean validate(String userInput, HttpSession session) {
String storedCaptcha = (String) session.getAttribute("captcha");
return userInput != null && userInput.equalsIgnoreCase(storedCaptcha);
}
}
集成到Web应用
在Servlet或Spring Boot中返回验证码图片,并设置Session。
@RestController
public class CaptchaController {
@GetMapping("/captcha")
public ResponseEntity<byte[]> getCaptcha(HttpSession session) throws IOException {
String captchaText = CaptchaGenerator.generateCaptcha();
session.setAttribute("captcha", captchaText);
byte[] imageBytes = CaptchaImageGenerator.generateImage(captchaText);
return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(imageBytes);
}
}
增强安全性措施
- 限制验证码有效时间(如5分钟过期)。
- 禁止同一验证码重复使用。
- 添加滑动验证或行为验证(如Google reCAPTCHA)补充。
前端调用示例
HTML通过<img>标签加载验证码,表单提交时携带用户输入。

<img src="/captcha" onclick="this.src='/captcha?t=' + Date.now()" />
<input type="text" name="captcha" placeholder="输入验证码" />






