java如何实现验证码
使用Java生成图形验证码
在Java中生成图形验证码可以通过BufferedImage和Graphics2D类实现。以下是一个简单示例:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;
public class CaptchaGenerator {
private static final String CHAR_SET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final int WIDTH = 120;
private static final int HEIGHT = 40;
private static final int CODE_LENGTH = 4;
private static final int LINE_COUNT = 20;
public static String generate(OutputStream out) throws Exception {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// 设置背景色
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
// 生成随机验证码
Random random = new Random();
StringBuilder captcha = new StringBuilder();
for (int i = 0; i < CODE_LENGTH; i++) {
int index = random.nextInt(CHAR_SET.length());
char c = CHAR_SET.charAt(index);
captcha.append(c);
// 绘制字符
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.setFont(new Font("Arial", Font.BOLD, 30));
g.drawString(String.valueOf(c), 20 + i * 25, 30);
}
// 添加干扰线
for (int i = 0; i < LINE_COUNT; i++) {
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT),
random.nextInt(WIDTH), random.nextInt(HEIGHT));
}
// 输出图像
ImageIO.write(image, "JPEG", out);
return captcha.toString();
}
}
验证码的存储与验证
生成的验证码需要与用户会话关联,通常存储在Session中:
// 生成验证码
String captcha = CaptchaGenerator.generate(response.getOutputStream());
request.getSession().setAttribute("captcha", captcha);
// 验证用户输入
String userInput = request.getParameter("captcha");
String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
if (userInput != null && userInput.equalsIgnoreCase(sessionCaptcha)) {
// 验证通过
} else {
// 验证失败
}
使用第三方库简化实现
Kaptcha是一个流行的Java验证码库:
-
添加Maven依赖:
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> -
配置Kaptcha:
@Bean public Producer kaptchaProducer() { Properties properties = new Properties(); properties.put("kaptcha.border", "no"); properties.put("kaptcha.textproducer.font.color", "black"); properties.put("kaptcha.textproducer.char.space", "5"); Config config = new Config(properties); DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha; } -
生成验证码:
@Autowired private Producer kaptchaProducer;
String text = kaptchaProducer.createText(); BufferedImage image = kaptchaProducer.createImage(text); request.getSession().setAttribute("captcha", text); ImageIO.write(image, "JPEG", response.getOutputStream());
### 防止自动化攻击的措施
增加验证码安全性:
- 设置验证码有效期(如5分钟过期)
- 限制验证码尝试次数
- 使用更复杂的验证码类型(如滑动验证码、行为验证码)
- 添加点击验证等交互方式
```java
// 设置过期时间
request.getSession().setAttribute("captcha_time", System.currentTimeMillis());
// 验证时检查过期
long generateTime = (Long) request.getSession().getAttribute("captcha_time");
if (System.currentTimeMillis() - generateTime > 5 * 60 * 1000) {
// 验证码已过期
}






