首先是要生成驗證碼:
package xx.xx
import java.io.*;
import java.util.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.image.*;
public class imageensure ...{
public imageensure() ...{
}
private char maptable[] = ...{'0', '1', '2', '3',
'4', '5', '6', '7', '8', '9'};
public string getensure(int width, int height, outputstream os) ...{
if (width <= 0)
width = 60;
if (height <= 0)
height = 20;
bufferedimage image = new bufferedimage(width, height,
bufferedimage.type_int_rgb);
// 獲取圖形上下文
graphics g = image.getgraphics();
// 設(shè)定背景色
g.setcolor(new color(0xdccccc));
g.fillrect(0, 0, width, height);
//畫邊框
g.setcolor(color.black);
g.drawrect(0, 0, width - 1, height - 1);
// 取隨機產(chǎn)生的認證碼
string strensure = "";
// 4代表4位驗證碼
for (int i = 0; i < 4; ++i) ...{
strensure += maptable[(int) (maptable.length * math.random())];
}
// 將認證碼顯示到圖象中
g.setcolor(color.red);
g.setfont(new font("atlantic inline", font.plain, 14));
//畫的具體坐標
string str = strensure.substring(0, 1);
g.drawstring(str, 8, 14);
str = strensure.substring(1, 2);
g.drawstring(str, 20, 15);
str = strensure.substring(2, 3);
g.drawstring(str, 35, 18);
str = strensure.substring(3, 4);
g.drawstring(str, 45, 15);
// 釋放圖形上下文
g.dispose();
try ...{
// 輸出圖象到頁面
imageio.write(image, "jpeg", os);
} catch (ioexception e) ...{
return "";
}
return strensure;
}
}
然后是調(diào)用,可以在頁面調(diào)用,也可以在servlet中調(diào)用,我推薦是單獨的一個servlet調(diào)用,在頁面調(diào)用可能會出現(xiàn)異常,但是不影響使用。在servlet中寫上如下的代碼:
||| //禁用緩存,每次訪問此頁面,都重新生成
response.setheader("pragma","no-cache");
response.setheader("cache-control","no-cache");
response.setdateheader("expires", 0);
//生成驗證碼的實例對象
imageensure ie = new imageensure();
//調(diào)用里面的方法,返回的是生成的驗證碼中的字符串
string str = ie.getensure(0,0,response.getoutputstream());
//獲得session,并把字符串保存在session中,為后面的對比做基礎(chǔ)
httpsession session = request.getsession();
session.setattribute("strensure", str);
然后把servlet內(nèi)嵌到具體的網(wǎng)頁中,具體嵌入就是用dreamweaver在需要插入驗證碼的地方插入圖像,地址就指向此servlet即可。
輸入驗證碼并提交后,在新的頁面中可以按如下方法判斷:
<body>
<%
//session的默認存在時間為20分鐘,如果20分鐘不輸入驗證碼,session將會消失,因此要做下判斷
if(session.getattribute("strensure")==null)
...{
%>
<jsp:forward page="imageerr.jsp"/>
<%
}else...{
//獲取在session中保存的生成驗證碼的數(shù)字
string ensure = (string)session.getattribute("strensure");
//獲取在頁面的表單中輸入的驗證碼
string code = request.getparameter("txtimage");
//判斷輸入的驗證碼,跟保存的生成的驗證碼是否一樣
if(ensure.equals(code) && code != null)
...{
%>
<jsp:forward page="searchword?method=add"/>
<%
}else...{
%>
<jsp:forward page="imageerr.jsp"/>
<%
}
}
%>
</body>
新聞熱點
疑難解答