JAVA生成验证码

好记性不如赖笔头……

1、生成验证码

    //设置验证码的宽度
        int width = 120;
        //设置验证码的调度
        int height = 30;
        //创建对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //创建画笔
        Graphics graphics = image.getGraphics();
        //设置颜色
        graphics.setColor(Color.GREEN);
        //填充背景颜色(要除去边框)
        graphics.fillRect(1, 1, width-2, height-2);

        //设置颜色
        graphics.setColor(Color.red);
        //画边框
        graphics.drawRect(0, 0, width-1, height-1);

        //设置颜色
        graphics.setColor(Color.BLACK);
        //设置字体
        graphics.setFont(new Font("黑体", Font.BOLD, 20));
        //创建随机数对象
        Random random = new Random();
        //循环生成四个随机数
        for (int i = 0; i < 4; i++) {
            //将四个随机数写入到图片中
            graphics.drawString(random.nextInt(10)+"", 20*(i+1), 20);

        }

        //设置颜色
        graphics.setColor(Color.PINK);
        //设置干扰线数量
        for (int i = 0; i < 9; i++) {
            //随机生成9条不同位置的干扰线
            graphics.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));

        }

        //将图片以jpg格式输出到resp中
        ImageIO.write(image, "jpg", resp.getOutputStream());

2、调用验证码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>验证码</title>
<script type="text/javascript">
    function changeCode(){
        //根据ID获取img标签
        var code = document.getElementById("checkCode");
        //给img标签的src属性重新赋值并发送请求
        code.src="/httpServletResponse/index3?timestamp="+new Date().getTime();
    }
</script>
</head>
<body>
<form action="#" method="post">
    用户名:<input type="text" name="userName"/><br/>
    密&nbsp;&nbsp; 码:<input type="password" name="userPwd"/><br/>
    验证码:<input type="text" name="code"/><img src="/httpServletResponse/index3" id="checkCode" onclick="changeCode();" ><a href="javascript:changeCode();">换一张</a><br/>
    <input type="submit" value="登陆"/>
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值