2023年12月18日发(作者:)

验证码技术的实现按如下步骤:

1、设计一个验证码生成类

import .*;

import .*;

import .*;

import O;

public class RandomImageGenerator {

final static int LENGTH=4;

static Color

colors[]={,,,,};

public static String random() {//创建一个4位的验证码字符串

String

str="1234567890ABCDEFGHIJKLMNOPORSTUVWXYZabcefghijklmnopqrstuvwxyz",rand="";

random=new ();

for(int i=0;i

int

index=t(());

rand+=ing(index,index+1);

}

return rand;

}

public static void render(String num,OutputStream out)

throws IOException {//创建一幅含有验证码的干扰图象,送输出流

if (()!=LENGTH)

throw new IllegalArgumentException("验证码长度不足");

int height=30;

int width=(height-10)*LENGTH;

BufferedImage bi=new

BufferedImage(width,height,_INT_RGB);

Graphics2D g=(Graphics2D)phics();

random=new ();

or();

ct(0,0,width,height);

Font mFont=new Font("宋体",+,height-5);

t(mFont);

FontMetrics fm=tMetrics();

//画干扰点

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

int x=t(width);

int y=t(height);

Color color1=new

Color(t(255),t(255),t(255));

or(color1);

al(x,y,0,0);

}

//画干扰线

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

int x=0;

int y=t(height);

int x1=width;

int y1=t(height);

Color color1=new

Color(t(255),t(255),t(255));

or(color1);

ne(x,y,x1,y1);

}

//显示验证码字符

char str[]=Array();

for(int i=0,x=0,y=0;i<;i++) {

y=cent();

if (i%2==0){

y-=10;

}

or(colors[t()]);

ars(str,i,1,x,y);

x+=dth(str[i])+5;

}

e();

(bi,"jpg",out);

}

}

2.使用Servlet程序来实现验证码

在页面中使用这个Servlet程序,显示验证码图案。

import t.*;

import .*;

import .*;

public class RandomImageServlet extends HttpServlet {

public final static String

RANDOM_LOGIN_KEY="RANDOM_LOGIN_KEY";

public void init() throws ServletException {

perty("ss","true");//设置一个系统属性

}

public String getRandomLoginKey(HttpServletRequest

request){

return

(String)sion().getAttribute(RANDOM_LOGIN_KEY);

}

protected void doGet(HttpServletRequest

request,HttpServletResponse response)

throws

ServletException,IOException {

HttpSession session=sion();

if (session!=null){

String

randomString=();//得到一个6位的验证码字符串

ribute(RANDOM_LOGIN_KEY , randomString);//验证码保存到session中

tentType("image/jpeg");//设置响应类型为jpeg类型

der("Pragma","No-cache");//设置响应不采用缓冲

der("Cache-Control","no-cache");//设置响应不采用缓冲

eHeader("Expires",

0);//设置响应不采用缓冲

(randomString,putStream());

}

}

protected void doPost(HttpServletRequest

request,HttpServletResponse

response) throws ServletException,IOException {

doGet(request,response);

}

}

在WEB-INF/中配置这个Servlet程序:

image

ImageServlet

image

/

页面实现

验证码

type="text" id="random">

width="100" height="20" border="1" align="absmiddle">

href="JavaScript:reloadImage('./');">看不清楚,换一张

在Eclipse按上述步骤完成后,点击“运行”,界面上验证码图标总是显示不出来,出现一把叉,究竟是什么原因,在网上查找了很久,大多数都说是要下载类似flash插件,或者是Cookie禁用等方法,我按网上的方法改来改去,最后都是不行,最后我把里的配置一个一个重新加进去,发现,竟然是在

里面配置了过滤器导致的。把这个过滤器的配置去掉,嘿嘿,竟然可以正常显示验证码图标了,问题得以解决,花了好长好长时间啊。