JSP驗證碼大全之中文驗證碼(源碼)
??? 在上一篇內容中介紹了有關JSP中產生數字驗證碼圖片的過程,本文將繼續介紹有關JSP中的另一種驗證碼的實現,即中文驗證碼在JSP中的實現,使用中文驗證碼的好處是能提高驗證的有效性,提高驗證的安全度,因為中文相對于英文或數字筆畫結構相對比較復雜,從而增加了分析程序解析驗證碼圖片并讀取驗證信息的難度。在文中并分析中文驗證的實現過程。
???二、JSP中實現中文驗證碼源碼如下:
ChineseVal.jsp
<%@
page?
pageEncoding
=
"gb2312" contentType="image/jpeg"
import
=
"javax.imageio.*,java.util.*,java.awt.image.*,java.awt.*"
%>
<%!
???
//在此處
獲取并生成隨機顏色
??? Color getRandColor(Random random,
int
ff,
int
cc) {
??????
if
(ff > 255)
?????????? ff = 255;
??????
if
(cc > 255)
?????????? cc = 255;
??????
int
r = ff + random.nextInt(cc - ff);
??????
int
g = ff + random.nextInt(cc - ff);
??????
int
b = ff + random.nextInt(cc - ff);
??????
return
new
Color(r, g, b);
??? }
%>
<%
???
//在此處
設置JSP頁面無緩存
??? response.setHeader(
"Pragma"
,
"No-cache"
);
??? response.setHeader(
"Cache-Control"
,
"no-cache"
);
??? response.setDateHeader(
"Expires"
, 0);
???
//
設置圖片的長寬
???
int
width = 130;
????int?height = 30;
???
//設定被隨機選取的中文字,此處中文字內容過多,不一一列出,只是舉例說明下。
??? String base =
"\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u538b\u6162\u53d4\u80cc\u7ec6...省略文字。。。"
;
??? //設置 備選隨機漢字的個數
???
int
length = base.length();
???
//
創建緩存圖像
??? BufferedImage image =
new
BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
???
//
獲取圖像
??? Graphics g = image.getGraphics();
???
//
創建隨機函數的實例
??? Random random =
new
Random();
??? //此處 設定圖像背景色
??? g.setColor(getRandColor(random, 188, 235));
??? g.fillRect(0, 0, width, height);
???
//設置隨機
備選的字體類型
??? String[] fontTypes = {
"\u5b8b\u4f53"
,
"\u65b0\u5b8b\u4f53"
,
??????????
"\u9ed1\u4f53"
,
"\u6977\u4f53"
,
"\u96b6\u4e66"
};
???
int
fontTypesLength = fontTypes.length;
???
//
在圖片背景上增加噪點,增加圖片分析難度
??? g.setColor(getRandColor(random, 180, 199));
??? g.setFont(
new
Font(
"Times New Roman"
, Font.PLAIN, 14));
???
for
(
int
i = 0; i < 4; i++) {
?????? g.drawString(
"@*@*@*@*@*@*@*"
,
?????? 0, 5 * (i + 2));
??? }
???
//
取隨機產生的驗證碼
(4
個漢字
)
???
//
保存生成的漢字字符串
??? String sRand =
""
;
???
for
(
int
i = 0; i < 4; i++) {
??????
int
start = random.nextInt(length);
?????? String rand = base.substring(start, start + 1);
?????? sRand += rand;
??????
//
設置圖片上字體的顏色
?????? g.setColor(getRandColor(random, 10, 150));
??????
//
設置字體格式
?????? g.setFont(
new
Font(fontTypes[random.nextInt(fontTypesLength)],
?????? Font.BOLD, 18 + random.nextInt(6)));
??????
//
將此漢字畫到驗證圖片上面
?????? g.drawString(rand, 24 * i + 10 + random.nextInt(8), 24);
??? }
??? // 將驗證碼存入S ession中
??? session.setAttribute(
"rand"
, sRand);
??? g.dispose();
???
//將
圖象輸出到JSP頁面中
??? ImageIO.write(image,
"JPEG"
, response.getOutputStream());
??? //關閉流
??? out.clear();
??? out=pageContext.pushBody();??
%>
???下文將介紹有關JSP中文驗證碼的亂碼問題解決方法以及JSP中調用以上兩種驗證碼的方法。
?
鳳凰涅槃/浴火重生/馬不停蹄/只爭朝夕
???? 隱姓埋名/低調華麗/簡單生活/完美人生
posted on 2008-11-29 01:57 poetguo 閱讀(28624) 評論(50) 編輯 收藏 所屬分類: JSP 、JAVA