----发个随机验证码示例

  1. public void doGet(HttpServletRequest request, HttpServletResponse response) 
                throws ServletException, IOException { 
    
            response.setContentType("text/html;charset=GBK"); 
            PrintWriter out = response.getWriter(); 
            //ServletOutputStream out=response.getOutputStream(); 
            //定义数组储存验证码 
            char[] strChar=new char[]{'a','b','c','d','e','f','g','h','k','j','想','中','天','地','华','1','2','3','4','5','6','7','8','9','0'}; 
            //位图 
            BufferedImage image=new BufferedImage(60,50,BufferedImage.TYPE_INT_RGB); 
            Graphics gra=image.getGraphics(); 
            //设置背景色 
            gra.setColor(Color.white); 
            gra.fillRect(0, 0, 60, 50); 
            //设置字体以及大小 
            gra.setColor(Color.red); 
            gra.setFont(new Font("宋体",Font.BOLD,15)); 
            String strTest=""; 
            char strNum=0; 
            //生成随机种子 
            Random r=new Random(new Date().getTime()); 
            //循环得到4个随机值 
            for (int i = 0; i < 4; i++) { 
                //确定随机值 
                strNum=strChar[r.nextInt(strChar.length)]; 
                //存储验证码 
                strTest+=strNum; 
                //描绘验证码 
                gra.drawString(Character.toString(strNum), i*15, 35); 
            } 
            System.out.println(strTest); 
            //转码上色输出 
    //      com.sun.image.codec.jpeg.JPEGImageEncoder encoder=com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(out); 
    //      encoder.encode(image); 
            //在servlet上显示有颜色,这里我保存在作用域中,注释上两行以及outputStream,49行 
            //在页面上加上背景图片显色,字体颜色不会显示 
            request.setAttribute("strTest", strTest); 
            request.getRequestDispatcher("../main.jsp").forward(request, response); 
             
             
             
             
             
             
             
             
             
             
             
        }
    

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值