网页生成验证码技术

后台servlet代码如下:

//告诉客户端此响应的格式
        response.setContentType("image/jpeg");

        int width = 80;
        int height = 40;
        //设置验证码图片的宽、高以及图片类型(这里是RGB类型)
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //拿到一个Graphics对象
        Graphics g = img.getGraphics();
        //绘制背景
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);

        //设置字体
        g.setFont( new Font("黑体",Font.BOLD,18));
        //以毫秒时间为种子创建一个随机数生成器
        Random r = new Random(new Date().getTime());

        for(int i=0;i<4;i++){
            //生成随机数字0-9
            int a = r.nextInt(10);
            int y = 10+r.nextInt(20);
            //生成随机颜色
            Color c = new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255));
            g.setColor(c);
            //将数字画到图片中
            g.drawString(""+a, 5+i*width/4, y);
        }

        //绘制干扰线
//      for(int i=0;i<10;i++){
//          Color c = new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255));
//          g.setColor(c);
//          g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
//      }

        //绘制干扰点
        for(int i=0;i<100;i++){
            Color c = new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255));
            g.setColor(c);
            int x = r.nextInt(width);
            int y = r.nextInt(height);

            g.drawLine(x, y, x, y);
        }

        //类似于流中的close()带动flush()---把数据刷到img对象当中
        g.dispose();
        ImageIO.write(img, "jpeg", response.getOutputStream());

浏览器端代码如下:

<html>
  <head>
    <title>模拟登陆界面</title>
    <script type="text/javascript">
        function changeImg(){
            var imgNode = document.getElementById("imgId");
            var t = new Date().getTime();
            imgNode.src = "/JavaWeb/img?"+t;
        }
    </script>
  </head>
  <body>
    用户名:<input type="text" name="name"/><br/><br/>
    密    码:<input type="password" name="pwd"/><br/><br/>
    验证码:<input type="text" name="name"/>
         <img id="imgId" src="/JavaWeb/img"/>
         <a href="javascript:changeImg()">看不清</a><br/>
         <input type="submit" value="登录"/>
  </body>
</html>

值得一提的小技巧是,在js中,img的src后面带了个以时间毫秒数的参数t,保证每次请求都不同,以实现验证码更换功能,加入不带参数,浏览器以为是同一个请求,根据缓存机制,不会像服务器端发请求消息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值