美文网首页
13. response 验证码实现

13. response 验证码实现

作者: 卡尔书院 | 来源:发表于2020-11-09 22:36 被阅读0次

前端实现验证码: js
后端实现: 需要用到java的图片类

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //浏览器5秒刷新
        resp.setHeader("refresh", "3");
        //在内存中创建一个图片
        BufferedImage image = new BufferedImage(80, 100, BufferedImage.TYPE_INT_RGB);
        //得到图片
        Graphics2D g = (Graphics2D)image.getGraphics();
        //设置图片的背景颜色
        g.setColor(Color.white);
        g.fillRect(0,0,80,20);
        //给图片写数据
        g.setColor(Color.blue);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0,20);
        //告诉浏览器这个响应用图片的形式打开
        resp.setContentType("image/png");
        //网站有缓存, 不让浏览器缓存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "nocache");
        //把图片写给浏览器
        boolean write = ImageIO.write(image, "png", resp.getOutputStream());

    }
    //生成随机数
    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7 - num.length(); i++){
            sb.append("0");
        }
        num = sb.toString()+num;
        return num;
    }
//生成随机数
    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        num = "0".repeat(Math.max(0, 7 - num.length())) +num;
        return num;
    }

相关文章

网友评论

      本文标题:13. response 验证码实现

      本文链接:https://www.haomeiwen.com/subject/lwbrbktx.html