zoukankan      html  css  js  c++  java
  • 生成随机数验证码的工具类(from韩顺平)

      生成随机数验证码的工具类

    package com.cx;
    //生成随机数的图片
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Random;
    
    import javax.imageio.ImageIO;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class CreateCode extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            //7.禁止浏览器缓存随机图片
            response.setDateHeader("Expires", -1);
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            
            //6.通知客户机以图片方式打开发送过去的数据
            response.setHeader("Content-Type", "image/jpeg");
            //1.在内存中创建一副图片
            BufferedImage image=new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB);
            //2.在图片上写数据
            Graphics g=image.getGraphics();
            
            //设背景色
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, 80, 30);
            
            //3.设置写入数据的颜色和字体
            g.setColor(Color.BLACK);
            g.setFont(new Font(null,Font.BOLD, 20));
            
            //4.向图片上写数据
            String num=makeNum();
            //将随机生成的数值保存到session
            request.getSession().setAttribute("checkcode", num);
            g.drawString(num, 0, 20);
            
            //5.把写好的数据的图片输出给浏览器
            ImageIO.write(image, "jpg", response.getOutputStream());
            
        }
        //该函数生成随机7位数
        public String makeNum(){
            Random r=new Random();
            //这里9999999可以生成7位
            String num=r.nextInt(9999)+"";
            StringBuffer sb=new StringBuffer();
            //如果不够4位,前面不补零
            for(int i=0;i<4-num.length();i++){
                sb.append("0");
            }
            num=sb.toString()+num;
            return num;
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            this.doGet(request, response);
        }
    
    }
    //使用
    //<img src="/验证码的url"/>
  • 相关阅读:
    day10 作业
    文件操作
    字符编码
    元组、字典、集合内置方法, 深浅拷贝
    day07作业
    一周总结
    mysql操作进阶
    mysql操作篇续
    mysql-操作篇
    mysql的安装
  • 原文地址:https://www.cnblogs.com/sunnyCx/p/7544109.html
Copyright © 2011-2022 走看看