2020-01-09 验证码的实现

前端代码:

看不清//验证码的图片标签以及切换验证码的标签


后端代码:

@RequestMapping(path = "/img")
    public void img(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("image/jpg");//设定返回的头文件,指定返回对象类型
//画验证码图片
        BufferedImage buffer = new BufferedImage(70, 35, BufferedImage.TYPE_INT_ARGB);创建缓存
        Random r = new Random();
        Graphics g = buffer.getGraphics();
        g.setColor(Color.black);
        g.fillRect(0, 0, 70, 35);
        String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
        String code = "";
        for (int i = 0; i < 4; i++) {
            int index = r.nextInt(codes.length());
            String c = "" + codes.charAt(index);
            float x = i * 1.0F * 70 / 4;
            Font f = new Font("黑体", 3, 24);
            g.setFont(f);
            g.setColor(new Color(r.nextInt(200), r.nextInt(200), r.nextInt(200)));
            g.drawString(c, (int) x, 30);
            code += c;
        }
        // 画干扰线
        for (int i = 0; i < 6; i++) {
            int x1 = r.nextInt(70);
            int y1 = r.nextInt(30);
            int x2 = r.nextInt(70);
            int y2 = r.nextInt(30);
            g.setColor(Color.BLUE);
            g.drawLine(x1, y1, x2, y2);
        }
        req.getSession(true).setAttribute("code", code);//将随机的验证码储存在session中,以用来之后用户输入验证码后进行比对
        ImageIO.write(buffer, "jpg", resp.getOutputStream());//通过流的形式输出
        

    }

你可能感兴趣的:(2020-01-09 验证码的实现)