[JavaWeb]Servlet实现验证码图片生成

目录

1.介绍

2.思路

3.代码


1.介绍

        使用servlet开发web时,如何在后端生成验证码,提供给前端使用。

2.思路

        使用Java自带的BufferImage类绘制。

3.代码

Serlet中的代码:

// 定义验证码图片大小
        final int width = 60;
        final int height = 30;
// 创建画板,绘制验证码
        BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
// 设置验证码图片的背景颜色
        graphics.setColor(Color.white);
        graphics.fillRect(0,0,width,height);
// 取验证码值,并绘制到图片上
        graphics.setColor(new     
        Color(getRandomInt(0,255),getRandomInt(0,255),getRandomInt(0,255)));
        String randomCode =getRandomCode();
        graphics.setFont(new Font("黑体",Font.BOLD,18));
        graphics.drawString(randomCode,15,20);
        response.setContentType("image/jpeg");

        graphics.setColor(new Color(getRandomInt(0,255),getRandomInt(0,255),getRandomInt(0,255)));
        graphics.drawLine(0,getRandomInt(0,height/2),width,getRandomInt(height/2,height));
        // 保存验证码到session
        request.getSession().setAttribute("VerifyCode",randomCode);
        ImageIO.write(bufferedImage,"jpg",response.getOutputStream());

辅助函数:

 /**
     * 获取指定范围的随机数
     * @param min
     * @param max
     * @return
     */
    private int getRandomInt(int min,int max){
        Random random = new Random();
        return random.nextInt(max - min + 1) + min;
    }


 /**
     * 获取随机字符串
     * @return
     */
    private String getRandomCode(){
        final String dics="1234567890abcdefghizklmnopqrstuvwxyzABCDEFGHIZKLMNOPQRSTUVWXYZ";
        int oneBit = getRandomInt(0,dics.length() - 1);
        int towBit = getRandomInt(0,dics.length() - 1);
        int threeBit = getRandomInt(0,dics.length() - 1);
        int fourBit = getRandomInt(0,dics.length() - 1);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(dics.charAt(oneBit));
        stringBuffer.append(dics.charAt(towBit));
        stringBuffer.append(dics.charAt(threeBit));
        stringBuffer.append(dics.charAt(fourBit));
        return stringBuffer.toString();
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值