2、WEB开发由浅入深系列BLOG-2(Servlet编写验证码)

1、用Servlet返回相应的文件的时候我们就调用response.setContextType(“image/JPEG”);方法就可以了,这次的案例是写一个验证码的案例。代码和注释内容如下所示:
 
private static Random ran = new Random(); //声明一个静态的random全局变量
 
--准备工作.一个得到随即验证码文字的方法,一个随即颜色的方法,一个得到反色颜色的方法
//得到验证码的文字
 
    public String getRamdomString(){
       char[] cs = {'1','2','3','4','5','6','7','8','9','A'};
       StringBuffer sb = new StringBuffer();   //创建sb拼装验证码String
       for(int i=0 ; i < 6 ; i++){
           char a = cs[ran.nextInt(cs.length)];   //用random搭配数组的length方法,得到数组的随即字节
           sb.append(String.valueOf(a));
       }         
       return sb.toString();
    }
    //获得随即的颜色
    public Color getBackColor(){
       return new Color(ran.nextInt(225),ran.nextInt(225),ran.nextInt(225));
    }
    //获得颜色的反色
    public Color getReverseColor(Color c){
       return new Color(225-c.getRed(),225-c.getGreen(),225-c.getBlue());
    }
 
 
 
//生成验证码的方法
public void doGet(HttpServletRequest request, HttpServletResponseresponse)
           throws ServletException, IOException {
 
       response.setContentType("image/JPEG"); //设置返回文件格式
      
       String code = this.getRamdomString(); //得到随即字符串
       Color backcolor = this.getBackColor();   //得到背景颜色
       Color reverseColor= this.getReverseColor(backcolor); //得到背景色的反色
       int width = 100;
       int height = 30;
       //new一个图片流,有长度,宽度和type3个参数
       BufferedImage bi = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
       Graphics2D gg= bi.createGraphics();    //得到绘画工具
       Font f = new Font(Font.SANS_SERIF,Font.BOLD,16);   //声明一个font
       gg.setFont(f);
       gg.setColor(backcolor);            //设置背景色
       gg.fillRect(0, 0, width, height);   //绘制背景
       gg.setColor(reverseColor);         //设置绘画工具反色背景色
       gg.drawString(code, 18, 20);       //写字符串验证码宽18,高20开始
       for(int i = 0 ; i < 100 ; i++){    //画100个噪点
           gg.setColor(new Color(ran.nextInt(225),ran.nextInt(225),ran.nextInt(225)));
           gg.drawRect(ran.nextInt(width), ran.nextInt(height),1,1); //限制宽,高范围
       }
       ServletOutputStream sos = response.getOutputStream();   //得到返回对象
       JPEGImageEncoder jie = JPEGCodec.createJPEGEncoder(sos);//得到编码器。
       jie.encode(bi);          //将bi编码至图片
       bi.flush();          //写至客户端
      
       sos.close();
    }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值