• java生成验证码


    @RequestMapping(value="/123.html")
        public void yaz(HttpServletResponse response,HttpServletRequest request) throws Exception{
            
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("text/html;charset=utf-8");
            int width=80;int height=40;
            //画板
            BufferedImage b =new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
            //工具
            Graphics g= b.getGraphics();
            
            g.setColor(new Color(40, 200, 255));
            g.fillRect(0, 0, width, height);
            
            char[] ch="QWERTYUIOPASDFGHJKLZXCVBNM1234567890".toCharArray();
            Random random = new Random();
            int len = ch.length,index;
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < 4; i++) {
                index = random.nextInt(len);
                g.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
                g.setFont(new Font("微软雅黑", Font.BOLD, 18));
                g.drawString(ch[index]+"", i*15+3, 18);
                sb.append(ch[index]);
            
            }
            //干扰线
            for(int i=1;i<10000;i++){
                g.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
                g.drawLine(random.nextInt(i*3+2), random.nextInt(i*5+1), random.nextInt(i*3+1),random.nextInt(i*9));
            }
            
            //结束
            g.dispose();
            b.flush();
            //保存
            request.getSession().setAttribute("yzm", sb.toString());
            try {
                //输出图片到页面
                ImageIO.write(b, "png", response.getOutputStream());
            } catch (IOException e) {
                
            }
            
            
        }

    前台页面怎么用?

    <body>
    
    <!-- 图片的路径直接是验证码的请求路径即可 -->
    <img alt="" src="<%=request.getContextPath()%>/123.html" id="reload" onclick="reload2()">
    
    <script type="text/javascript">
    function reload2(){
        var time = new Date().getTime();
        document.getElementById("reload").src="<%=request.getContextPath()%>/123.html?d="+time;
    }
    //为什么请求多了一个参数呢?  是为了告诉浏览器这是一个不同的请求,否则验证码不刷新
    
    
    </script>
    
    
    
    </body>
  • 相关阅读:
    [CF603C] Lieges of Legendre
    [CF1070A] Find a Number
    [CF431D] Random Task
    2020牛客暑期多校训练营(第二场)C
    2020牛客暑期多校训练营(第二场)F
    2020牛客暑期多校训练营(第二场)D
    2020牛客暑期多校训练营(第一场)H
    [CF1000E] We Need More Bosses
    Java学习2 (ThreadLocal)
    Java复习1
  • 原文地址:https://www.cnblogs.com/syscn/p/5794391.html
Copyright © 2020-2023  润新知