現在許多系統的註冊 登錄或者發布信息模塊都添加的隨機驗證碼功能 就是為了避免自動註冊程序或者自動發布程序的使用
驗證碼實際上就是隨機選擇壹些字符以圖片的形式展現在頁面上 如果進行提交操作的同時需要將圖片上的字符同時提交 如果提交的字符與服務器session保存的不同 則認為提交信息無效 為了避免自動程序分析解析圖片 通常會在圖片上隨機生成壹些幹擾線或者將字符進行扭曲 增加自動識別驗證碼的難度
在這裏 我們使用java實現驗證碼
<%@ page contentType= image/jpeg import= java awt * java awt image * java util * javax imageio * %>
<%!
Color getRandColor(int fc int bc){//給定範圍獲得隨機顏色
Random random = new Random();
if(fc> ) fc= ;
if(bc> ) bc= ;
int r=fc+random nextInt(bc fc);
int g=fc+random nextInt(bc fc);
int b=fc+random nextInt(bc fc);
return new Color(r g b);
}
%>
<%
//設置頁面不緩存
response setHeader( Pragma No cache );
response setHeader( Cache Control no cache );
response setDateHeader( Expires );
// 在內存中創建圖象
int width= height= ;
BufferedImage image = new BufferedImage(width height BufferedImage TYPE_INT_RGB);
// 獲取圖形上下文
Graphics g = image getGraphics();
//生成隨機類
Random random = new Random();
// 設定背景色
g setColor(getRandColor( ));
g fillRect( width height);
//設定字體
g setFont(new Font( Times New Roman Font PLAIN ));
// 隨機產生 條幹擾線 使圖象中的認證碼不易被其它程序探測到
g setColor(getRandColor( ));
for (int i= ;i< ;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= ;i< ;i++){
int a=random nextInt(codeList length() );
String rand=codeList substring(a a+ );
sRand+=rand;
// 將認證碼顯示到圖象中
g setColor(new Color( +random nextInt( ) +random nextInt( ) +random nextInt( )));//調用函數出來的顏色相同 可能是因為種子太接近 所以只能直接生成
g drawString(rand *i+ );
}
// 將認證碼存入SESSION
session setAttribute( rand sRand);
// 圖象生效
g dispose();
// 輸出圖象到頁面
ImageIO write(image JPEG response getOutputStream());
out clear();
out = pageContext pushBody();
lishixinzhi/Article/program/Java/hx/201311/25536