用Java写一个验证码功能
时间: 2024-03-16 17:47:01 浏览: 110
java写的一个验证码
3星 · 编辑精心推荐
好的,以下是一个简单的 Java 验证码功能的示例代码:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CaptchaUtil {
private static final String CAPTCHA_COOKIE_NAME = "captcha_key";
private static final String CAPTCHA_SESSION_ATTRIBUTE_NAME = "captcha_key";
private static final int CAPTCHA_LENGTH = 6;
private static final int CAPTCHA_WIDTH = 120;
private static final int CAPTCHA_HEIGHT = 40;
private static final int CAPTCHA_FONT_SIZE = 20;
private static final int CAPTCHA_EXPIRATION_TIME = 5 * 60; // 5 minutes
public static void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
// Generate random captcha text
String captchaKey = generateRandomCaptchaKey(CAPTCHA_LENGTH);
// Set captcha key in session
HttpSession session = request.getSession();
session.setAttribute(CAPTCHA_SESSION_ATTRIBUTE_NAME, captchaKey);
// Set captcha key in cookie with expiration time
Cookie captchaCookie = new Cookie(CAPTCHA_COOKIE_NAME, captchaKey);
captchaCookie.setMaxAge(CAPTCHA_EXPIRATION_TIME);
captchaCookie.setPath(request.getContextPath() + "/");
response.addCookie(captchaCookie);
// Generate captcha image
BufferedImage captchaImage = generateCaptchaImage(captchaKey);
// Write captcha image to response output stream
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(captchaImage, "png", outputStream);
outputStream.close();
}
public static boolean validateCaptcha(HttpServletRequest request) {
// Get captcha key from session and cookie
HttpSession session = request.getSession();
String captchaSessionKey = (String) session.getAttribute(CAPTCHA_SESSION_ATTRIBUTE_NAME);
Cookie[] cookies = request.getCookies();
String captchaCookieKey = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(CAPTCHA_COOKIE_NAME)) {
captchaCookieKey = cookie.getValue();
break;
}
}
}
// Validate captcha key
if (captchaSessionKey == null || captchaCookieKey == null || !captchaSessionKey.equals(captchaCookieKey)) {
return false;
}
// Remove captcha key from session and cookie
session.removeAttribute(CAPTCHA_SESSION_ATTRIBUTE_NAME);
Cookie captchaCookie = new Cookie(CAPTCHA_COOKIE_NAME, null);
captchaCookie.setMaxAge(0);
captchaCookie.setPath(request.getContextPath() + "/");
response.addCookie(captchaCookie);
return true;
}
private static String generateRandomCaptchaKey(int length) {
String captchaKey = "";
Random random = new Random();
for (int i = 0; i < length; i++) {
captchaKey += (char) (random.nextInt(26) + 'a');
}
return captchaKey;
}
private static BufferedImage generateCaptchaImage(String captchaKey) {
BufferedImage captchaImage = new BufferedImage(CAPTCHA_WIDTH, CAPTCHA_HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics graphics = captchaImage.getGraphics();
// Draw background
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT);
// Draw captcha text
graphics.setColor(Color.BLACK);
graphics.setFont(new Font("Arial", Font.BOLD, CAPTCHA_FONT_SIZE));
graphics.drawString(captchaKey, 10, 25);
// Draw noise
graphics.setColor(Color.GRAY);
for (int i = 0; i < 50; i++) {
graphics.drawLine(random.nextInt(CAPTCHA_WIDTH), random.nextInt(CAPTCHA_HEIGHT), random.nextInt(CAPTCHA_WIDTH), random.nextInt(CAPTCHA_HEIGHT));
}
return captchaImage;
}
}
```
这个验证码功能使用了 Servlet API 和 Java 2D 图形库,可以在 Servlet 环境中使用。它生成一个随机的长度为 6 的验证码字符串,并在 session 和 cookie 中保存验证码字符串。它还生成一个包含验证码字符串的 PNG 图片,可以直接写入 HTTP 响应输出流中。在验证验证码时,它从 session 和 cookie 中检索验证码字符串,并比较它们是否相等。如果验证成功,它将从 session 和 cookie 中删除验证码字符串。
阅读全文