ValidateCode验证码

//在servlet中 写一个可以生成验证码的程序

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        HttpSession session=request.getSession();

        response.setHeader("pragma", "no-catch");
        response.setHeader("cache-control", "no-catch");
        response.setHeader("expires", "0");

        ValidateCode code = new ValidateCode(120, 25, 4, 8);
        String  veticode=code.getCode();
        session.setAttribute("realcode", veticode);
        code.write(response.getOutputStream());

    }

    private void test(HttpServletResponse response) throws IOException {
        int width = 120,height=25;
        //生成一张图片
        BufferedImage  img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics grap = img.getGraphics();//得到一个画笔

        //填充背景色
        grap.setColor(Color.PINK);
        //设置填充的区域
        grap.fillRect(1, 1, width-2, height-2);

        //设置边框的颜色
        grap.setColor(Color.RED);
        grap.drawRect(0, 0, width-1, height-1);

        //设置字体
        grap.setFont(new Font("黑体", Font.BOLD|Font.ITALIC, 18));

        //向图片上写字
        Random r = new Random();
        int p = 15;
        for(int i=1;i<=4;i++)
        {
            grap.drawString(r.nextInt(10)+"", p,20);
            p+=15;
        }

        //向图片上画线
        for(int i=1;i<=10;i++)
        {
            grap.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }
        //把图片发送给客户端
        ImageIO.write(img, "jpg", response.getOutputStream());

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    doGet(request, response);
    }
}

//在jsp中的程序如下:
   
<script type="text/javascript">
       function fun()
       {
                var img = document.getElementById("image");
                img.src="/Moon/servlet/checkcode?u=1"+new Date().getTime();
       }

    </script>

  
      验证码:<input   align="center"  type="text" name="code" width=150px height=25px>
             <img id="image" src='/Moon/servlet/checkcode'>
             <a href="javascript:fun()">换一张<a/><br/><br/>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值