此演示代碼主要包括以下三部分:
1.checkCode.java:用於生成驗證碼
2.checkCodeServler
3.check.jsp 驗證
下面是checkCode.java的內容:
復制代碼 代碼如下:
//用於獲取四位隨機數
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();
// 設定背景色
g.setColor(new Color(0xDCCCCC));
g.fillRect(0, 0, width, height);
// 畫邊框
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
// 取隨機產生的認證碼
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; //返回生成的隨機數
}
再是checkCodeServlet的內容
復制代碼 代碼如下:
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();
//調用裡面的方法,返回的是生成的驗證碼中的字符串
String str = ie.getEnsure(0,0,response.getOutputStream());
//獲得session,並把字符串保存在session中,為後面的對比做基礎
HttpSession session = request.getSession();
session.setAttribute("strEnsure", str);
}
然後是web.xml對servlet的配置
復制代碼 代碼如下:
<servlet>
<servlet-name>CheckServlet</servlet-name>
<servlet-class>com.blog.servlet.CheckServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckServlet</servlet-name>
<url-pattern>/check</url-pattern>
</servlet-mapping>
最後是jsp頁面的引用
復制代碼 代碼如下:
<html>
<head>
<title>驗證碼</title>
<script type="text/javascript" language="javascript">
//重新獲取驗證字符
function changeImage()
{
//單擊觸發圖片重載事件,完成圖片驗證碼的更換
document.getElementById("imgRandom").src = document.getElementById("imgRandom").src + '?';
}
</script>
</head>
<body>
<img alt= "看不清楚?點擊更換驗證碼 " src= "check" width= "100" height= "50" id="imgRandom" onclick="changeImage()"/>
<a href="javascript:changeImage();">看不清?</a>
</body>
</html>
在jsp頁面中,只需要將img的src的屬性指向生成驗證碼的servlet就可以了,指向servle在web.xmlt映射的url。