CAPTCHA--验证码

验证码开发有两种方法:

1.自己用代码画一个

2.调用ValidateCode.jar工具包

第一种方式:

创建一个动态web工程

编写一个Servlet,在该Servlet内进行如下操作

验证码开发步骤:

1.在内存中创建一个图片对象

1                 int width = 110;
2         int height = 25;
3         // 在内存中创建一个图片对象
4         BufferedImage img = new BufferedImage(width, height,
5                 BufferedImage.TYPE_INT_RGB);    
View Code

2.创建一个画笔

1     //创建一个画笔
2         Graphics g=img.getGraphics();

3.给图片添加背景颜色

1     //给图片添加背景色
2         g.setColor(Color.PINK);
3         g.fillRect(1, 1, width-2, height-2);

4.给图片边框一个颜色

1 //给边框一个颜色
2         g.setColor(Color.RED);
3         g.drawRect(0, 0, width-1, height-1);

5.设置文本样式

1 //设置文本样式
2         g.setColor(Color.BLUE);
3         g.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 13));

6.添加文本内容

1     //添加文本内容
2         Random r = new Random();
3         int position =20;
4         for(int i=0;i<4;i++){
5             g.drawString(r.nextInt(9)+" ", position, 20);
6             position+=20;
7         }

7.绘制干扰线

1 //绘制干扰线(循环九条干扰线)
2         for(int i=0;i<9;i++){
3             g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
4         }

8.将图片以流的方式输出客户端

1 //将图片以流的方式输出客户端
2         ImageIO.write(img, "jpg", response.getOutputStream());

第二种方式:

直接使用工具包即可。

1     //width:宽度
2         //height:高度
3         //codeCount:验证码个数
4         //lineCount:干扰线数量
5         ValidateCode vc = new ValidateCode(110, 25, 4, 9);
6         vc.write(response.getOutputStream()); 

猜你喜欢

转载自www.cnblogs.com/aWangZaiNuLi/p/10373969.html