[置頂] 工作筆記5.JAVA圖片驗證碼
來源:程序員人生 發布時間:2014-11-07 09:02:13 閱讀次數:2137次
本文主要內容為:利用JAVA圖片制作驗證碼。
設計思路:
1、拷貝AuthImageServlet.class圖片驗證碼
2、配置web.xml
3、JSP中,調用封裝好的AuthImageServlet,實現加載驗證碼的功能,
4、取出寄存在Session中的驗證碼,在Action中判斷驗證碼的正確性
相比較上1篇博客《工作筆記5.JAVA文本框驗證碼》而言,圖片驗證碼增加了安全性。
在Action中,通過取出Session中的驗證碼與輸入的驗證碼是不是匹配進行判斷。
步驟:
1、拷貝AuthImageServlet.class圖片驗證碼
下載地址: http://pan.baidu.com/s/1bnF7dcr
2、配置web.xml
<servlet>
<servlet-name>AuthImageServlet</servlet-name>
<servlet-class>cn.bjjczb.jyzgcx.util.AuthImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AuthImageServlet</servlet-name>
<url-pattern>/servlet/AuthImageServlet</url-pattern>
</servlet-mapping>
3、JSP中,調用封裝好的AuthImageServlet,實現加載驗證碼的功能
<script type="text/javascript">
function changeCode() {
var imgNode = document.getElementById("vimg");
//重新加載驗證碼,到達刷新的目的
imgNode.src = "${pageContext.request.contextPath}/servlet/AuthImageServlet?t=" + Math.random(); // 避免閱讀器緩存的問題
}
</script>
驗證碼:
<input type="text" id="creditCodes" name="creditCodes" class="dz" style="width: 110px;"/>
<img id="vimg" src="${pageContext.request.contextPath}/servlet/AuthImageServlet" class="code" style="vertical-align: middle;" width="83" height="21" />
<a href="#" onclick="changeCode();">刷新</a>
4、取出寄存在Session中的驗證碼,在Action中判斷驗證碼的正確性
/** 登錄 */
public String login() throws Exception {
// 獲得寄存在Session中的驗證碼
String creditCode = (String) session.getAttribute("rand");
//比較深輸入的"驗證碼creditCodes"與creditCode是不是匹配(疏忽大小寫)
if (creditCodes.equalsIgnoreCase(creditCode)) {
//驗證碼輸入正確
} else {
//驗證碼輸入毛病
}
}
//用于獲得頁面中用戶輸入的驗證碼
private String creditCodes;
public String getCreditCodes() {
return creditCodes;
}
public void setCreditCodes(String creditCodes) {
this.creditCodes = creditCodes;
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈