zoukankan      html  css  js  c++  java
  • 生成一个简单的javaweb验证码

    只是生成一个验证码图片

    import javax.imageio.ImageIO;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.Random;
    
    public class ImageServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //Set the browser refresh time
            resp.setHeader("refresh","4");
            //Set image size
            BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
            //Make a brush
            Graphics g = image.getGraphics();
            //Set the brush color
            g.setColor(Color.white);
            //The background of the fill image is white
            g.fillRect(0,0,80,20);
            //Set the brush color to pink
            g.setColor(Color.pink);
            g.setFont(new Font("null",Font.BOLD,20));
            //Draw a seven-digit number
            g.drawString(makeNum(),0,20);
            //Set the browser's content type to image
            resp.setContentType("image/jpg");
            //Disable browser caching
            resp.setDateHeader("expires",-1);
            resp.setHeader("Cache-Control","no-cache");
            resp.setHeader("Pragma","no-cache");
            //Displays images to the client
            ImageIO.write(image,"jpg",resp.getOutputStream());
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
        }
        private String makeNum(){
            Random r = new Random();
            //Pseudorandom generates a seven-digit number
            String num = String.valueOf(r.nextInt(9999999));
            StringBuilder s = new StringBuilder();
            //If there are fewer than seven digits, add a 0 in front of it.
            for (int i = 0; i < 7-num.length(); i++){
                s.append("0");
            }
            num = s.toString()+num;
            return num;
        }
    }
    
    
  • 相关阅读:
    python中字典排序,列表中的字典排序
    Python模块:operator简单介绍
    java 物理资源回收 finally与try
    Eclipse相对路径
    java Lambda
    java 匿名内部类
    java File类
    java单例类
    java 创建子类
    jvm运行时数据区域
  • 原文地址:https://www.cnblogs.com/tanjiangtao/p/12951244.html
Copyright © 2011-2022 走看看