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");

    }            

 

你可能感兴趣的:(servlet)