zoukankan      html  css  js  c++  java
  • servlet生成数字验证码

    servlet生成一个数字验证码

    1.设置背景

    private void setBackGround(Graphics g) {
            g.setColor(Color.orange);
            g.fillRect(0, 0, WIDTH, HEIGHT);
        }

    2.得到图片框

    private void setBorder(Graphics g) {
            g.setColor(Color.black);
            g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
        }

    3.画干扰线

    private void drawRandomLine(Graphics g) {
            g.setColor(Color.green);
            for (int i = 0; i < 4; i++) {
                g.drawLine((new Random()).nextInt(WIDTH),
                        (new Random()).nextInt(HEIGHT),
                        (new Random()).nextInt(WIDTH),
                        (new Random()).nextInt(HEIGHT));
            }
        }

    4.写随机数

    private void drawRandomNUM(Graphics2D g,StringBuffer sb) {
            g.setColor(Color.blue);
            g.setFont((new Font("华文新魏", Font.BOLD, 30)));
            String base = "0123456789";
            int x = 10;
            for (int i = 0; i < 4; i++) {
                int degree = (new Random()).nextInt() % 30;// 旋转度数
                char ch = base.charAt((new Random()).nextInt(base.length()));
                g.rotate(degree * Math.PI / 180, x, 25);
                g.drawString(ch + "", x, 25);
                g.rotate(-degree * Math.PI / 180, x, 25);
                x += 20;
                sb.append(ch);
            }
        }

    5.doGet调用

        private static final int WIDTH = 100;//初始化图片大小
        private static final int HEIGHT = 35;
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            StringBuffer sb=new StringBuffer();//用于存放生成的数字字符串
            BufferedImage bi = new BufferedImage(WIDTH, HEIGHT,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = bi.getGraphics();
            setBackGround(g);// 1、设置背景
            setBorder(g);// 2、设置边框
            drawRandomLine(g);// 3、画干扰线
            drawRandomNUM((Graphics2D) g,sb);// 4、写随机数
            // 5、将图片发送浏览器
            response.setHeader("content-type", "image/jpeg");
            ImageIO.write(bi, "jpg", response.getOutputStream());
                    //6.设置属性,便于验证码比较
         request.getSession().setAttribute(NoticeConstant.CHECK_ENCODING,sb.toString());
            // 控制浏览器不要缓存
            response.setHeader("Expires", -1+"");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("pragma", "no-cache");
        }            
  • 相关阅读:
    [Jenkins] TestComplete 使用Jenkins进行持续集成测试
    selenium 使用close和quit关闭driver的不同点
    sleep和wait的区别
    Appium-测试失败后获取屏幕截图的方法
    sql优化的几种方式
    【Fine学习笔记】python 文件l操作方法整理
    【Fine学习笔记】Xcode的快捷方式
    【Fine学习笔记】Jmeter笔记
    【Fine原创】常见的HTTP错误码的具体含义整理
    【Fine原创】JMeter分布式测试中踩过的那些坑
  • 原文地址:https://www.cnblogs.com/jamsbwo/p/4586161.html
Copyright © 2011-2022 走看看