写在前面前段时间大家说最近大环境不好,很多公司都在裁员。如果换工作,不建议轻易辞职,但我想说的是,我所在的公司欺诈百出,业务需求层出不穷。招不到的人也不少。。。我最近也很忙,但还是要抽出时间来自查记录。最近也写了一个简单的小功能,就是登录界面的图片验证码功能环境:Tomcat9,Jdk1.81生成验证码的工具类publicclassRandomValidateCodeUtil{publicstaticfinalStringRANDOMCODEKEY="RANDOMVALIDATECODEKEY";//session中的keyprivateStringrandString="0123456789";//只随机生成数字字符串privateString//privateStringrandString="ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机生成只包含字母的字符串//privateStringrandString="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机生成一串数字和字母privateintwidth=95;//图片宽度privateintheight=25;//图片高度privateintlineSize=40;//干涉线数privateintstringNum=4;//随机生成的字符数privatestaticfinalLoggerlogger=LoggerFactory.getLogger(RandomValidateCodeUtil.class);私人随机随机=新随机();/***获取字体*/privateFontgetFont(){returnnewFont("Fixedsys",Font.CENTER_BASELINE,18);}/***获取颜色*/privateColorgetRandColor(intfc,intbc){if(fc>255)fc=255;如果(bc>255)bc=255;intr=fc+random.nextInt(bc-fc-16);intg=fc+random.nextInt(bc-fc-14);intb=fc+random.nextInt(bc-fc-18);返回新颜色(r,g,b);}/***生成随机图像*/publicvoidgetRandcode(HttpServletRequestrequest,HttpServletResponseresponse){HttpSessionsession=request.getSession();//BufferedImage类是带有缓冲区的Image类,Image类是用来描述图像信息的类BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_BGR);Graphicsg=image.getGraphics();//生成Image对象的Graphics对象,改变对象对图像进行各种绘制操作g.fillRect(0,0,width,height);//图片大小g.setFont(newFont("TimesNewRoman",Font.ROMAN_BASELINE,18));//字体大小g.setColor(getRandColor(110,133));//字体颜色//绘制干涉线对于(inti=0;i<=lineSize;i++){drowLine(g);}//绘制随机字符StringrandomString="";for(inti=1;i<=stringNum;i++){randomString=drowString(g,randomString,i);}logger.info(randomString);//将生成的随机字符串保存到会话中session.removeAttribute(RANDOMCODEKEY);session.setAttribute(RANDOMCODEKEY,randomString);g.处置();try{//将内存中的图像以流动的形式输出到客户端ImageIO.write(image,"JPEG",response.getOutputStream());}catch(Exceptione){logger.error("无法将内存中的图片通过流式输出到客户端>>>>",e);}}/***绘制字符串*/privateStringdrawString(Graphicsg,StringrandomString,inti){g.setFont(getFont());g.setColor(新颜色(random.nextInt(101),random.nextInt(111),random.nextInt(121)));字符串rand=String.valueOf(getRandomString(random.nextInt(randString.length())));随机字符串+=随机数;g.translate(random.nextInt(3),random.nextInt(3));g.drawString(rand,13*i,16);返回随机字符串;}/***绘制干扰线*/privatevoiddrawLine(Graphicsg){intx=random.nextInt(width);inty=random.nextInt(height);intxl=random.nextInt(13);intyl=random.nextInt(15);g.drawLine(x,y,x+xl,y+yl);}/***获取随机字符*/publicStringgetRandomString(intnum){returnString.valueOf(randString.charAt(num));}}这个类不用动,直接用2页代码
