Servlet生成验证码

Servlet生成验证码

重写doGet和doPost方法

1. java代码
        // 图片高度
        private static final int IMG_HEIGHT = 100;
        // 图片宽度
        private static final int IMG_WIDTH = 30;
        // 验证码长度
        private static final int CODE_LEN = 4;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        浏览器每分钟刷新一次
        resp.setHeader("refresh","60");

        BufferedImage bi = new BufferedImage(IMG_HEIGHT, IMG_WIDTH, BufferedImage.TYPE_INT_RGB);

        // 获取绘图工具
        Graphics graphics = bi.getGraphics();

        // 使用RGB设置背景颜色
        graphics.setColor(new Color(100, 230, 200));

        // 填充矩形区域
        graphics.fillRect(0, 0, 100, 30);

        // 验证码中所使用到的字符
        char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
        StringBuilder captcha = new StringBuilder();

        // 存放生成的验证码
        Random random = new Random();
        for(int i = 0; i < CODE_LEN; i++) {

            // 循环将每个验证码字符绘制到图片上
            int index = random.nextInt(codeChar.length);

            // 随机生成验证码颜色
            graphics.setColor(new Color(random.nextInt(150), random.nextInt(200), random.nextInt(255)));

            // 将一个字符绘制到图片上,并制定位置(设置x,y坐标)
            graphics.drawString(codeChar[index] + "", (i * 20) + 15, 20);
            captcha.append(codeChar[index]);
        }

        // 将生成的验证码code放入session中
        req.getSession().setAttribute("code", captcha.toString());

        // 通过ImageIO将图片输出
        ImageIO.write(bi, "png", resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

代码来源

2. web.xml代码
<servlet>
    <servlet-name>image</servlet-name>
    <servlet-class><!-->类文件<--></servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>image</servlet-name>
    <url-pattern>/image</url-pattern>
</servlet-mapping>
3. 实例图

posted on 2023-01-06 23:10  lsyorha  阅读(24)  评论(0编辑  收藏  举报