Java基于Servlet 验证吗

req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 图像的上下文
        Graphics g = image.getGraphics();

        // 处理验证码区域的颜色
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);

        // 设置边框
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);

        // 生成验证码
        Random random = new Random();
        String codeSession = "";
        for (int i = 0; i < length; i++)
        {
            String chaStr = String.valueOf(charset[random.nextInt(charset.length)]);
            codeSession += chaStr;
            g.setColor(Color.blue);
            g.setFont(new Font("宋体", Font.BOLD, 30));

        }
        g.drawString(codeSession, drawX, drawY);

        req.setAttribute("codeSession", codeSession);

        // 设置干扰点
        for (int i = 1; i < 155; i++)
        {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            g.setColor(Color.red);
            g.drawOval(x, y, 0, 0);
        }
        resp.setDateHeader("Expires", -1);// 设定网页到期时间,一时过期则必到服务器上重新请求
        resp.setHeader("Cache-Control", "no-cache");// 不能cache
        resp.setHeader("Pragma", "no-cache");// 禁止浏览器从本地cache中调税内容

        // 把imagewrite写入outpustream
        ImageIO.write(image, "jpeg", resp.getOutputStream());

 

 

 

效果如图:

posted on 2014-01-04 08:04  peter.peng  阅读(116)  评论(0编辑  收藏  举报