private static int WIDTH=120;
private static int HEIGHT=25;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//不要缓存
resp.setHeader("Expires", "-1");
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Pragma", "no-cache");
//得到代表内存图片的对象bufferedImage
BufferedImage image=new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_3BYTE_BGR);
//得到该图片的画笔Graphics
Graphics g= image.getGraphics();
//画边框
g.drawRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLUE);
//填充背景色
g.setColor(Color.YELLOW);
g.fillRect(1, 1, WIDTH-2, HEIGHT-2);
//画干扰线
g.setColor(Color.GRAY);
Random r=new Random();
for(int i=0;i<29;i++){
g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT), r.nextInt(WIDTH), r.nextInt(HEIGHT));
}
//画随即验证码
g.setColor(Color.RED);
g.setFont(new Font("宋体",Font.BOLD,20));
int x=20;
for(int i=0;i<4;i++){
g.drawString(r.nextInt(10)+"", x, 20);
x+=20;
}
//输出
ImageIO.write(image, "jpg", resp.getOutputStream());
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}