當前位置:法律諮詢服務網 - 企業資訊 - 如何用java實現驗證碼

如何用java實現驗證碼

目前,許多系統的註冊、登錄或信息發布模塊都增加了隨機驗證碼功能,以避免使用自動註冊程序或自動發布程序。

驗證碼其實就是隨機選取壹些字符以圖片的形式顯示在頁面上。如果圖片上的字符需要同時提交,如果提交的字符與服務器會話中存儲的字符不同,則提交的信息被視為無效。為了避免程序自動分析分析圖片,通常會在圖片上隨機生成壹些幹擾線或者扭曲字符,以增加驗證碼自動識別的難度。

這裏我們用java實現驗證碼。

& lt% @ page content type = image/JPEG import = Java awt * Java awt image * Java util * javax imageio * % & gt;

& lt%!

color Get rand color(int fc int BC){//獲取給定範圍內的隨機顏色。

Random Random = new Random();

if(fc & gt;)fc =;

if(BC & gt;)BC =;

int r = fc+random nextInt(BC fc);

int g = fc+random nextInt(BC fc);

int b = fc+random nextInt(BC fc);

返回新顏色(r g b);

}

% & gt

& lt%

//設置頁面不被緩存

response set header(Pragma No cache);

response setHeader(緩存控制無緩存);

response setDateHeader(過期);

//在內存中創建圖像

int width = height =

buffered image image = new buffered image(width height buffered image TYPE _ INT _ RGB);

//獲取圖形上下文

graphics g = image get graphics();

//生成隨機類

Random Random = new Random();

//設置背景顏色

g set color(getRandColor());

g fillRect(寬度高度);

//設置字體

g setFont(新字體(Times New Roman Font PLAIN));

//隨機的幹擾線使得圖像中的認證碼很難被其他程序檢測到。

g set color(getRandColor());

for(int I =;我& lt;i++)

{

int x = random nextInt(width);

int y = random nextInt(height);

int XL = random nextInt();

int yl = random nextInt();

g drawLine(x y x+XL y+yl);

}

//取隨機生成的認證碼(數字)

string codeList = ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz;

string sRand =;

for(int I =;我& lt;i++){

int a = random nextInt(codeList length());

string rand = codeList substring(a a+);

sRand+= rand;

//在圖像中顯示驗證碼。

g set Color(new Color(+random nextInt()+random nextInt()+random nextInt());//調用函數生成的顏色是壹樣的,可能是因為種子太近了,所以只能直接生成。

g抽繩(rand * I+);

}

//在會話中存儲身份驗證代碼。

session set attribute(rand sRand);

//圖像生效

g dispose();

//將圖像輸出到頁面

ImageIO write(image JPEG response get output stream());

out clear();

out = pageContext push body();

Lishi Xinzhi/Article/program/Java/hx/201311/25536

  • 上一篇:怎麽搜索公司怎麽搜索公司的營業執照
  • 下一篇:長清銀行是壹家怎樣的銀行?
  • copyright 2024法律諮詢服務網