首先创建一个简单的随机数字型的验证码
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int height = 25,width = 120;
BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = bimage.getGraphics();
g.setColor(Color.BLUE);
g.drawRect(0, 0, width, height);
g.setColor(Color.YELLOW);
g.fillRect(1, 1, width-1, height-1);
g.setColor(Color.GRAY);
Random random = new Random();
for (int i = 0; i < 20; i++) {
g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height ));
}
g.setColor(Color.RED);
g.setFont(new Font("黑体",Font.BOLD|Font.ITALIC,20));
for (int i = 0; i < 4; i++) {
g.drawString(random.nextInt(9)+"", 20+(i*10), 20);
}
response.setHeader("Content-Type", "image/jpeg");
ImageIO.write(bimage, "jpg", response.getOutputStream());
}
完整的验证码功能将在之后提交(因为我也不会)