码迷,mamicode.com
首页 > 其他好文 > 详细

servlet生成数字验证码

时间:2015-06-18 17:12:42      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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生成数字验证码

标签:

原文地址:http://www.cnblogs.com/jamsbwo/p/4586161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!