生成一个简单的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;
    }
}

posted @ 2020-05-24 15:53  起美了  阅读(163)  评论(0编辑  收藏  举报