资源描述:
《java网页实现验证码》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、1、jsp实现方式CheckCode.jsp<%@pagecontentType="image/jpeg"import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"%><%!ColorgetRandColor(intfc,intbc){//给定范围获得随机颜色 Randomrandom=newRandom(); if(fc>255)fc=255; if(bc>255)bc=255; intr=fc+random.n
2、extInt(bc-fc); intg=fc+random.nextInt(bc-fc); intb=fc+random.nextInt(bc-fc); returnnewColor(r,g,b); }%><%//设置页面不缓存response.setHeader("Pragma","No-cache");response.setHeader("Cache-Control","no-cache");response.setDateHeader("Expires",0);//在内存中创
3、建图象intwidth=60,height=20;BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//获取图形上下文Graphicsg=image.getGraphics();//生成随机类Randomrandom=newRandom();//设定背景色g.setColor(getRandColor(200,250));g.fillRect(0,0,width,height);//设定字体g.setFont(newFont("
4、TimesNewRoman",Font.PLAIN,18));//画边框//g.setColor(newColor());//g.drawRect(0,0,width-1,height-1);//随机产生155条干扰线,使图象中的认证码不易被其它程序探测到g.setColor(getRandColor(160,200));for(inti=0;i<155;i++){ intx=random.nextInt(width); inty=random.nextInt(height); intxl=ra
5、ndom.nextInt(12); intyl=random.nextInt(12); g.drawLine(x,y,x+xl,y+yl);}//取随机产生的认证码(4位数字)StringsRand="";for(inti=0;i<4;i++){ Stringrand=String.valueOf(random.nextInt(10)); sRand+=rand; //将认证码显示到图象中 g.setColor(newColor(20+random.nextInt(110),20+rando
6、m.nextInt(110),20+random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 g.drawString(rand,13*i+6,16);}//将认证码存入SESSIONsession.setAttribute("rand",sRand);//图象生效g.dispose();//输出图象到页面ImageIO.write(image,"JPEG",response.getOutputStream());out.clear();out=pageContext.pu
7、shBody();%>使用方法: 验证方法:Stringrand=(String)session.getAttribute("ran
8、d");StringCheckCode=request.getParameter("CheckCode");if(rand.equals(CheckCode)) { //out.print("成功"); response.sendRedirect(