无插件及工具纯java生成验证码

1:html页面

<body>
<image id="code" src="DemoServlet"></image>
<input type="button" value="看不清,换一张" id="btn" οnclick="changeCode(this)" >
<script type="text/javascript">
function changeCode(obj){
    document.getElementById("btn").isDisabled=true;
    document.getElementById("code").src='DemoServlet?ts='+new Date().getTime();
}
</script>
</body>

2:后台java代码(servlet  doGet方法中

//生成图片中的字符
        String str = "abcdefghjklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        //创建随机对象
        Random rand = new Random();
        //设置验证码图片展示的宽高
        int width = 100;
        int height = 30;
        //创建图片缓冲对象
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //获取出作图对象
        Graphics graphics = img.getGraphics();
        //设置背景颜色
        graphics.setColor(Color.gray);
        //设置填充一个矩形
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.black);
        //参数1,2是线条起点坐标,3,4是线条终点坐标
        graphics.drawLine(5, 10, 100, 25);
        graphics.setColor(Color.blue);
        graphics.drawLine(10, 30, 100, 30);
        graphics.setColor(Color.red);
        graphics.drawLine(15, 15, 100, 20);
        graphics.setColor(Color.white);
        graphics.drawLine(20, 10, 100, 18);
        
        for (int i = 0; i < 4; i++) {
            graphics.setColor(Color.black);
            int nextInt = rand.nextInt(str.length());
            String substring = str.substring(nextInt, nextInt+1);
            //填充文字及文字所在的xy坐标的起点
            graphics.drawString(substring, width/5*(i+1), 15);
        }
        //输出
        ImageIO.write(img, "jpg", resp.getOutputStream());

 

通过上边的方法可以派生出加减乘除的验证码:将随机字符全部改为数字(0-9),添加加减乘除符号字符串,

随机获取出数字和符号即可

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值