JAVA验证码的实现【转】

本文介绍了一种使用Java生成验证码的方法,包括设置页面属性、生成随机颜色、绘制底色、干扰线及字符等步骤,并提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:



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

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(); 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值