`
mimang2007110
  • 浏览: 232578 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

JAVA验证码的实现【转】

阅读更多
思路:



做验证码其实就是在画图,我们可以把它的步骤比如成如下的几个动作: 

1.画出一个矩形,用做底色这个矩形大小也是验证码的底色. 
2.画出若干条干扰线. 
3.画字符.比如验证码有四个,那么就是要画四个字符,这个字符当然是可以随机的,每画一个字符我们就用一个StringBuffer来接连保存,画完后把这个StringBuffer对象存到session中,最后以图片的形式显示这个JSP页面. 

方法: 


先要设置页面的PAGE属性:

<%@ page language="java" contentType="image/jpg;charset=gb2312" %>

我们在这里先写一个产生随机颜色的方法:

Color getRandColor(int min,int max){   //随机产生指定区域内的RGB颜色

  Random random1=new Random();

  if(min>=255)min=255;

  if(max>=255)max=255;

  int r=min+random1.nextInt(max-min);

  int g=min+random1.nextInt(max-min);

  int b=min+random1.nextInt(max-min);

  return new Color(r,g,b);

 }

//禁止页面缓冲

  response.setHeader("Pragma","No-cache");

 response.setHeader("Cache-Control","no-cache");

 response.setDateHeader("Expires",0);

 //在缓存中创建图形对象,然后输出

 int width=60,height=20;  //输出图片的大小

 BufferedImage buff=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);  //指定缓冲的图片和颜色结构

 Graphics g=buff.getGraphics();   //得到绘图对象

利用graphics对象我们就可以画图了:

矩形:

g.setColor(getRandColor(200,250));

 g.fillRect(0,0,width,height);

干扰线:(循环的画出细小的线条)

for(int i=1;i<=30;i++){

  int x=rand.nextInt(width);  //线条的起始位置

  int y=rand.nextInt(height);

  int tx=rand.nextInt(12);

  int ty=rand.nextInt(12);

  g.drawLine(x,y,x+tx,y+ty);

 }

验证码:

String coding="";  //保存得到的验证码字符串

 for(int i=0;i<4;i++){

  String temp=String.valueOf(rand.nextInt(10));  //0-9的数字

  coding+=temp;

  //显示验证码,20-140色段

  g.setColor(getRandColor(20,140));

  g.drawString(temp,13*i+6,16);

 }

 //信息存入session

 session.setAttribute("code",coding);

清空缓存区:(这一步非常重要,不然服务器会报错误)

g.dispose();

 ServletOutputStream sos=response.getOutputStream();

 ImageIO.write(buff,"jpeg",sos);

 sos.flush();  //强行将缓冲区的内容输入到页面

 sos.close();

 sos=null;

 response.flushBuffer();

 out.clear();

 //Return a new BodyContent object, save the current "out" JspWriter, and update the value of the "out" attribute in the page scope attribute namespace of the PageContext

 out=pageContext.pushBody(); 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics