//用于獲取四位隨機數(shù)
private char mapTable[] = {'0','1','2','3','4','5','6','7','8','9'};
//生成驗證碼,并返回隨機生成的數(shù)字
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)生的認(rèn)證碼
String strEnsure = "";
// 4代表4位驗證碼
for (int i = 0; i 4; ++i){
strEnsure += mapTable[(int) (mapTable.length * Math.random())];
}
// 將認(rèn)證碼顯示到圖象中
g.setColor(Color.red);
g.setFont(new Font("Atlantic Inline", Font.PLAIN, 14));
// 畫的具體坐標(biāo)
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; //返回生成的隨機數(shù)
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//禁用緩存,每次訪問此頁面,都重新生成
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
//生成驗證碼的實例對象
CheckCode ie = new CheckCode();
//調(diào)用里面的方法,返回的是生成的驗證碼中的字符串
String str = ie.getEnsure(0,0,response.getOutputStream());
//獲得session,并把字符串保存在session中,為后面的對比做基礎(chǔ)
HttpSession session = request.getSession();
session.setAttribute("strEnsure", str);
}