add<验证码支持>
parent
61cb1dec77
commit
66449ed821
|
@ -0,0 +1,64 @@
|
|||
package example.controller;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Random;
|
||||
|
||||
@WebServlet("/captcha")
|
||||
public class CaptchaServlet extends HttpServlet {
|
||||
|
||||
// 处理生成验证码图片的请求
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
// 设置响应类型为图片
|
||||
response.setContentType("image/jpeg");
|
||||
|
||||
// 设置验证码内容
|
||||
String captchaText = generateCaptchaText();
|
||||
|
||||
// 将验证码存储到 session 中
|
||||
request.getSession().setAttribute("captcha", captchaText);
|
||||
|
||||
// 创建验证码图片
|
||||
BufferedImage image = new BufferedImage(100, 40, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D graphics = image.createGraphics();
|
||||
graphics.setColor(Color.WHITE);
|
||||
graphics.fillRect(0, 0, 100, 40);
|
||||
graphics.setFont(new Font("Arial", Font.BOLD, 30));
|
||||
graphics.setColor(Color.BLACK);
|
||||
graphics.drawString(captchaText, 10, 30);
|
||||
|
||||
// 输出验证码图片
|
||||
OutputStream out = response.getOutputStream();
|
||||
javax.imageio.ImageIO.write(image, "JPEG", out);
|
||||
out.close();
|
||||
}
|
||||
|
||||
// 生成随机的验证码文本
|
||||
private String generateCaptchaText() {
|
||||
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
StringBuilder captcha = new StringBuilder();
|
||||
Random random = new Random();
|
||||
for (int i = 0; i < 4; i++) {
|
||||
int index = random.nextInt(characters.length());
|
||||
captcha.append(characters.charAt(index));
|
||||
}
|
||||
return captcha.toString();
|
||||
}
|
||||
|
||||
// 检查用户提交的验证码是否正确(忽略大小写)
|
||||
public static boolean validateCaptcha(HttpServletRequest request, String userInputCaptcha) {
|
||||
String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
|
||||
if (sessionCaptcha == null) {
|
||||
return false; // 验证码已过期或不存在
|
||||
}
|
||||
return sessionCaptcha.equalsIgnoreCase(userInputCaptcha);
|
||||
}
|
||||
}
|
Reference in New Issue