java验证码如何实现
验证码生成与验证的实现步骤
生成验证码图片
使用Java的BufferedImage类创建验证码图片,结合Graphics2D绘制干扰线、噪点及随机字符。示例代码片段:
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.GRAY);
for (int i = 0; i < 5; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
// 绘制随机字符
String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
StringBuilder code = new StringBuilder();
for (int i = 0; i < 4; i++) {
String ch = String.valueOf(chars.charAt(random.nextInt(chars.length())));
code.append(ch);
g.setColor(new Color(random.nextInt(150), random.nextInt(150), random.nextInt(150)));
g.drawString(ch, 20 * i + 10, 25);
}
存储验证码信息
将生成的验证码字符串存入Session或Redis,用于后续验证:
request.getSession().setAttribute("captcha", code.toString());
// 或使用Redis(需配置连接)
redisTemplate.opsForValue().set("captcha_" + sessionId, code.toString(), 300, TimeUnit.SECONDS);
输出图片到响应流
通过ImageIO将图片写入HTTP响应:
response.setContentType("image/jpeg");
ImageIO.write(image, "JPEG", response.getOutputStream());
验证码校验逻辑
获取用户输入与存储值
从请求参数和Session/Redis中获取验证码进行比对:
String userInput = request.getParameter("captcha");
String storedCode = (String) request.getSession().getAttribute("captcha");
// 或从Redis获取
String storedCode = redisTemplate.opsForValue().get("captcha_" + sessionId);
执行比对与清理
忽略大小写比对后立即清除存储的验证码(防止重复使用):
if (storedCode != null && storedCode.equalsIgnoreCase(userInput)) {
request.getSession().removeAttribute("captcha");
// 或删除Redis中的key
redisTemplate.delete("captcha_" + sessionId);
return true; // 验证通过
}
return false;
进阶优化方案
增加安全措施
- 限制验证码请求频率(如1分钟内最多3次)
- 使用Token机制防止CSRF攻击
- 动态调整字符扭曲程度
使用第三方库简化
推荐库:
- Kaptcha:Google开源库,配置简单
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> - EasyCaptcha:支持多种风格(算术、中文等)
// 示例:生成算术验证码 ArithmeticCaptcha captcha = new ArithmeticCaptcha(); captcha.setLen(3); // 几位数运算 String code = captcha.getArithmeticString(); // 如"3+5=?"
移动端适配
- 返回Base64编码图片(非文件流)
- 行为验证码(如滑动拼图)方案集成
注意事项
- 验证码长度建议4-6位,避免过短(易破解)或过长(用户体验差)
- 生产环境应禁用调试日志,防止验证码值泄露
- 定期更换验证码字符集和样式模板







