一、创建ServletDemo继承HttpServlet,实现doGet和doPost方法

@WebServlet(urlPatterns = "/checkCodeServlet")
public class CheckServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int width = 100;
        int height = 30;
        String checkCodes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        int codeLen = 4;
        int lineCount = 20;
        int pointCount = 100;
        int spacing = width/codeLen;
        Random ran = new Random();
        StringBuilder sb = new StringBuilder();
        //创建画布
        BufferedImage bufferedImage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
        //创建画笔
        Graphics graphics = bufferedImage.createGraphics();
        //设置画笔颜色
        graphics.setColor(new Color(238,238,238));
        //填充背景
        graphics.fillRect(0,0,width,height);
        //设置字体
        Font font  = new Font("微软雅黑",Font.BOLD,20);
        if(font!=null){
            graphics.setFont(font);
        }
        //重设颜色
        graphics.setColor(new Color(162,162,162));
        //绘制干扰点
        for (int i = 0; i < pointCount; i++) {
            int x = MyUtils.getRanNum(0,width);
            int y = MyUtils.getRanNum(0,height);
            graphics.drawLine(x,y,x+1,y+1);
        }
        //重设颜色
        graphics.setColor(new Color(38,190,133));
        //绘制验证码
        for (int i = 0; i < codeLen; i++) {
            String code = String.valueOf(checkCodes.charAt(MyUtils.getRanNum(0,checkCodes.length())));
            int x = MyUtils.getRanNum(i*spacing,Math.abs((i+1)*spacing-font.getSize()/2));
            int y = MyUtils.getRanNum(font.getSize(),height);
            graphics.drawString(code, x,y);
            sb.append(code);
            System.out.println("x:"+x+"\ty:"+y);
        }
        //重设颜色
        graphics.setColor(new Color(148,218,248));
        //绘制干扰线
        for (int i = 0; i < lineCount; i++) {
            int x1 = MyUtils.getRanNum(0,width);
            int y1 = MyUtils.getRanNum(0,height);
            int x2 = MyUtils.getRanNum(x1,width);
            int y2 = MyUtils.getRanNum(y1,height);
            graphics.drawLine(x1,y1,x2,y2);
        }
        System.out.println(sb);
        request.getSession().setAttribute("checkCodeSession",sb.toString());
        ImageIO.write(bufferedImage,"png",response.getOutputStream());
    }
}

二、实际效果如下

这种验证码还是比较古老了,早已经不再安全了,写这篇文章就是为了记录一下验证码的简单绘制,不适合用于项目中的验证

原文作者:絷缘
作者邮箱:zhiyuanworkemail@163.com
原文地址:https://zhiyuandnc.github.io/zEKFZIKMH/
版权声明:本文为博主原创文章,转载请注明原文链接作者信息