1 public class CheckImage extends HttpServlet {
2 //验证码图片的宽度。
3 private int width=94;
4 //验证码图片的高度。
5 private int height=44;
6 protected void service(HttpServletRequest req, HttpServletResponse resp)
7 throws ServletException, java.io.IOException {
8 BufferedImage buffImg=new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
9 Graphics2D g=buffImg.createGraphics();
10 //创建一个随机数生成器类。
11 Random random=new Random();
12 g.setColor(Color.WHITE);
13 g.fillRect(0,0,width,height);
14 //创建字体,字体的大小应该根据图片的高度来定。
15 Font font=new Font("Times New Roman",Font.PLAIN,36);
16 //设置字体。
17 g.setFont(font);
18 //画边框。
19 g.setColor(Color.BLACK);
20 g.drawRect(0,0,width-1,height-1);
21
22 //随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。
23 g.setColor(Color.GRAY);
24 for (int i=0;i<160;i++){
25 int x = random.nextInt(width);
26 int y = random.nextInt(height);
27 int xl = random.nextInt(12);
28 int yl = random.nextInt(12);
29 g.drawLine(x,y,x+xl,y+yl);
30 }
31
32 //randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
33 StringBuffer randomCode=new StringBuffer();
34 int red=0,green=0,blue=0;
35 //随机产生4位数字的验证码。
36 for (int i=0;i<4;i++){
37 //得到随机产生的验证码数字。
38 String strRand=String.valueOf(random.nextInt(10));
39 //产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
40 red=random.nextInt(210);
41 green=random.nextInt(150);
42 blue=random.nextInt(150);
43 //用随机产生的颜色将验证码绘制到图像中。
44 g.setColor(new Color(red,green,blue));
45 g.drawString(strRand,20*i+8,36);
46 //将产生的四个随机数组合在一起。
47 randomCode.append(strRand);
48 }
49 //将四位数字的验证码保存到Session中。
50 HttpSession session=req.getSession();
51 session.setAttribute("validate",randomCode.toString());
52 //禁止图像缓存。
53 resp.setHeader("Pragma","no-cache");
54 resp.setHeader("Cache-Control","no-cache");
55 resp.setDateHeader("Expires", 0);
56 resp.setContentType("image/jpeg");
57 //将图像输出到Servlet输出流中。
58 ServletOutputStream sos=resp.getOutputStream();
59 ImageIO.write(buffImg, "jpeg",sos);
60 sos.close();
61 }
62 }