Servlet04

模拟登录

@WebServlet("/VerificationCode")
public class VerificationCode extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
            输出随机图片(CAPTCHA图像):
            Completely Automated Public Turing Test to Tell Computers and Humans Apart
            (全自动区分计算机和人类的测试)
            相关主要类(JDK 查看API)
            BufferedImage:内存图像
            Graphics:画笔
            ImageIO:输出图像
        */
        //1.创建BufferedImage对象
        int width = 120;
        int height = 30;
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);

        //2.获取Graphics对象
        Graphics g = bi.getGraphics();

        //3.添加背景颜色
        g.setColor(Color.PINK);
        g.fillRect(0, 0, width, height);

        //4.绘制干扰线
        Random r = new Random();

        for (int i = 0; i < 4; i++) {
            changeColor(i, g);
            //第一个点
            int x1 = r.nextInt(width);
            int y1 = r.nextInt(height);

            //第二个点
            int x2 = r.nextInt(width);
            int y2 = r.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        //5.绘制数字
        int left = 15;
        for (int i = 0; i < 4; i++) {
            int num = r.nextInt(10);
            changeColor2(i, g);
            g.drawString(num + "", left + i * 25, 20);
        }


        //6.输出图片,设置响应格式
        resp.setContentType("image/jpeg");
        ImageIO.write(bi, "JPEG", resp.getOutputStream());
    }

    public static void changeColor(int i, Graphics g) {
        if (i == 0) {
            g.setColor(Color.GREEN);
        } else if (i == 1) {
            g.setColor(Color.CYAN);
        } else if (i == 2) {
            g.setColor(Color.ORANGE);
        } else {
            g.setColor(Color.WHITE);
        }
    }

    public static void changeColor2(int i, Graphics g) {
        if (i == 0) {
            g.setColor(Color.BLACK);
        } else if (i == 1) {
            g.setColor(Color.BLUE);
        } else if (i == 2) {
            g.setColor(Color.MAGENTA);
        } else {
            g.setColor(Color.YELLOW);
        }
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
    <script>
        function freshCode() {
            var imgTag = document.getElementById("Code");
            //修改的值与原本的相同时,js不会访问后台
            imgTag.src = "/JavaWeb_war_exploded/VerificationCode?" + new Date().getTime();
        }
    </script>
</head>
<body>
<form>
    用户名:<input type="text"><br/>
    密码:<input type="password"><br/>
    请输入验证码:<input type="text">
    <img src="/JavaWeb_war_exploded/VerificationCode" id="Code"/>
    <a href="javascript:freshCode();">看不清,换一张</a>
    <br/>
</form>
</body>
</html>
上一篇:Android-Gradle-自动化多渠道打包(1),看完豁然开朗


下一篇:【Java】红黑树的删除操作概述和代码实现