image/jpeg 直接寫入 HttpServletResponse// 300+ 常用漢字 Unicode 字符串
String base = "\u7684\u4e00\u4e86\u662f\u6211..."; // 省略
char ch = base.charAt(new Random().nextInt(base.length()));
int degree = new Random().nextInt() % 30;
graphics.rotate(degree * Math.PI / 180, x, 23); // 旋轉
graphics.drawString(String.valueOf(ch), x, 23);
graphics.rotate(-degree * Math.PI / 180, x, 23); // 還原座標系
x += 30; // 下一字符位置
graphics.setColor(Color.MAGENTA);
for (int i = 0; i < 5; i++) {
graphics.drawLine(randomX(), randomY(), randomX(), randomY());
}
package com.sanrong;
import javax.servlet.http.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class test4Pic extends HttpServlet {
private static final int WIDTH = 130, HEIGHT = 30;
private static final String BASE = "\u7684\u4e00\u4e86..."; // 300+ 常用字
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
// 背景
g.setColor(Color.PINK);
g.fillRect(0, 0, WIDTH, HEIGHT);
// 邊框
g.setColor(Color.BLUE);
g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
// 干擾線
g.setColor(Color.MAGENTA);
Random r = new Random();
for (int i = 0; i < 5; i++)
g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT), r.nextInt(WIDTH), r.nextInt(HEIGHT));
// 驗證碼文字
g.setColor(Color.BLUE);
g.setFont(new Font("宋體", Font.BOLD, 20));
int x = 10;
for (int i = 0; i < 4; i++) {
char ch = BASE.charAt(r.nextInt(BASE.length()));
int deg = r.nextInt() % 30;
g.rotate(deg * Math.PI / 180, x, 23);
g.drawString(String.valueOf(ch), x, 23);
g.rotate(-deg * Math.PI / 180, x, 23);
x += 30;
}
resp.setContentType("image/jpeg");
ImageIO.write(img, "jpg", resp.getOutputStream());
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
web.xml 映射 /captcha.jpg<img src="/captcha.jpg" onclick="this.src='/captcha.jpg?'+Date.now()">doGet 中加入 session.setAttribute("captcha", code))session.getAttribute("captcha").equalsIgnoreCase(input)Curves 貝塞爾曲線干擾線Kaptcha、SimpleCaptcha 成熟庫替換手寫代碼本文提供開箱即用的中文圖形驗證碼 Servlet,涵蓋旋轉、干擾線、中文字庫等核心反爬蟲手段,適合中小項目快速接入;大型系統建議接入成熟庫或滑動/點選/行為驗證等更友好的驗證方式。