我們在做驗證碼的時候往往由於要反作弊,驗證有時故意加入多的干擾因素,這時驗證碼顯示不很清楚,使用者經常輸入錯誤。這樣不但要重新重新整理頁面,導致使用者沒有看清楚驗證碼而重填而不是修改,而且如果沒有用session儲存下使用者輸入的其它資料的話(如姓名),使用者剛剛輸入的內容也不存在了,這樣給使用者造成不好的體驗。
- 本例在原有驗證方式基礎之上增加一段js,通過xmlhttp來獲取返回值,以此來驗證是否有效,這樣即使使用者瀏覽器不支援js,也不會影響他的正常使用了。
- 為了防止作弊,當使用者連線3次輸入錯誤時則過載一下圖片,這樣也利於使用者因為圖片上的驗證碼辨認不清而使終無法輸入正確。
- 本例還特別適合檢驗使用者名稱是否有效,只要從後臺做個sql查詢,返回一個值或是xml即可。(這種例子太多 ,就在此不贅述了)。
- 本例的優點在於非常方便使用者輸入,而且減少對伺服器端的請求,可以說既改善使用者體驗而且略會節省頻寬成本,但相應地要在頁面上增加一段JavaScript程式碼,在目前網速越來越快人們要求便捷舒適的今天,似乎我們更應注意提供給使用者良好的使用感受。
程式碼如下,
1,img.jsp,輸入主頁面
<%@ page contentType="text/html; charset=GBK" language="java" import="java.sql.*" errorPage="" pageEncoding="GBK"%>
<%
//set Chinese Char
//Cody by JarryLi@gmail.com;
//homepage:jiarry.126.com
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
response.setContentType("text/html; charset=GBK");
%>
<html>
<head>
<title>圖片驗證</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<script src="net.js"></script>
</head>
<body>
AJAX(無重新整理及時提示)驗證碼例項!cody by jarry
<hr>
<%
String num=request.getParameter("num");
String random=(String)session.getAttribute("random");
String name=request.getParameter("name");
if(num!=null&&random!=null&&name!=null)
{
if(num.equals(random))
{
out.println("<font style=\"color:green;font-weight:bold\">恭喜您,驗證碼輸入成功,這裡是提交結果頁面,可以寫入資料庫了!</font> <a href=\"img.jsp\">返回再測試</a><br>");
out.println("您的名字是:"+name);
out.println("<br>");
out.println("您輸入的是:"+num);
out.println("驗證碼是:"+random);
out.println("</body>");
return;//javascript:history.go(-1)
}
}
%>
<script type="text/javascript">
var times=0;
function subform(){
var gtext=this.req.responseText;
var info=document.getElementById("info");
if(gtext.indexOf("validate_successful")!=-1){
//info.innerHTML="<font color=green>驗證碼通過</font>";
document.forms["myform"].submit();
//當得到的值表示合法,則驗證碼通過。
}else{
times++;
if(times>=3){//如果連線3次輸入錯誤,則過載圖片,可以防止作弊和使用者看不清圖片;
info.innerHTML="接連3次輸入錯誤。更新驗證碼,請重新輸入";
document.forms["myform"].num.value="";
show(document.getElementById('random'));
times=0;
}else{
info.innerHTML="第"+times+"次驗證碼錯誤,請注意區分大小寫 ";
}
document.forms["myform"].num.select();
}
}
function validata(obj){
var enter=true;
var info=document.getElementById("info");
var msg="";
if(obj.name.value.match(/^\s*$/g)){//如果未輸入名字,提示
msg+="請輸入您的姓名<br>";enter=false
}
if(obj.num.value.match(/^\s*$/g)){//如果未輸入驗證碼,提示
msg+="請輸入驗證碼<br>";enter=false
}
if(enter==false){
info.innerHTML=msg;
return false;
}
var url="num.jsp?num="+obj.num.value;
var newxmlhttp=new net.ContentLoader(url,subform,"","get",null,null);
return false;
}
function show(o){
//過載驗證碼
var timenow = new Date().getTime();
o.src="random.jsp?d="+timenow;
/*
//超時執行;
setTimeout(function(){
o.src="random.jsp?d="+timenow;
}
,20);
*/
}
</script>
<form action="img.jsp" name="myform" method="post" onsubmit="return validata(this);">
您的姓名:<input type="text" name="name" size=10> (為了更好地說明此例,特加姓名一項)<br>
驗 證 碼:<input type="text" name="num" size=10 maxlength="4"> <img src="random.jsp" id="random" align="" valign="absmiddle" hspace="5"> <a href="javascript:show(document.getElementById('random'))">驗證碼看不清</a><br>
<br> <input type="submit" value=" 提交 "><br>
<div id=info style="color:red;padding:10px;font-size:12px;"></div>
</form>
</body>
</html>
2,num.jsp,反饋xmlhttp請求的頁面
<%@ page contentType="text/html; charset=GBK" language="java" import="java.sql.*" errorPage="" pageEncoding="GBK"%>
<%
//set Chinese Char
//Cody by JarryLi@gmail.com;
//homepage:jiarry.126.com
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
response.setContentType("text/html; charset=GBK");
%>
<%
String num=request.getParameter("num");
String random=(String)session.getAttribute("random");
if(num!=null&&random!=null)
{
if(!num.equals(random))
{
/*
out.println("<script>alert('驗證碼錯誤!請重試。')</script>");
out.println("<script>history.go(-1)</script>");
//response.sendRedirect("img.jsp");
*/
out.print("validate_failed:"+random);
}
else
{
//out.println("<center>驗證成功!</center>");
out.print("validate_successful:"+random);
}
}
%>
3,random.jsp,生成驗證碼圖片的頁面
<%@ page autoFlush="false" import="java.util.*,java.awt.*,java.awt.image.*,com.sun.image.codec.jpeg.*,java.util.*" %>
<%
//set Chinese Char
//Cody by JarryLi@gmail.com;
//homepage:jiarry.126.com
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
response.setContentType("text/html; charset=GBK");
%>
<%
String chose="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
char display[]={'0',' ','0',' ','0',' ','0'},ran[]={'0','0','0','0'},temp;
Random rand=new Random();
for(int i=0;i<4;i++)
{
temp=chose.charAt(rand.nextInt(chose.length()));
display[i*2]=temp;
ran[i]=temp;
}
String random=String.valueOf(display);
session.setAttribute("random",String.valueOf(ran));
%>
<%
out.clear();
response.setContentType("image/jpeg");
response.addHeader("pragma","NO-cache");
response.addHeader("Cache-Control","no-cache");
response.addDateHeader("Expries",0);
int width=80, height=30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
//以下填充背景顏色
g.setColor(Color.GREEN);
g.fillRect(0, 0, width, height);
//設定字型顏色
g.setColor(Color.RED);
Font font=new Font("Arial",Font.PLAIN,20);
g.setFont(font);
//g.drawString(random,5,14);
g.drawString(random,5,20);
g.dispose();
ServletOutputStream outStream = response.getOutputStream();
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(outStream);
encoder.encode(image);
outStream.close();
%>
4,net.js,封裝好的xmlhttp物件,可以很方便的呼叫
/* namespacing object */
var net=new Object();
net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;
/*--- content loader object for cross-browser requests ---*/
net.ContentLoader=function(url,on_load,on_error,method,params,contentType){
this.req=null;
this.on_load=on_load;
this.on_error=(on_error) ? on_error : this.defaultError;
this.loadXMLDoc(url,method,params,contentType);
}
net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
if (!method)
{
method="GET";
}
if (!contentType && method=="POST")
{
contentType='application/x-www-form-urlencoded';
}
if (window.XMLHttpRequest)
{
this.req=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
//add try catch;
try {
this.req = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e1){
try {
this.req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2){
}
}
//
//this.req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (this.req)
{
try
{
var loader=this;
this.req.onreadystatechange=function()
{
net.ContentLoader.onReadyState.call(loader);
}
this.req.open(method,url,true);
if (contentType)
{
this.req.setRequestHeader('Content-Type', contentType);
}
this.req.send(params);
}
catch (err)
{
this.on_error.call(this);
}
}
}
net.ContentLoader.onReadyState=function(){
var req=this.req;
var ready=req.readyState;
if (ready==net.READY_STATE_COMPLETE){
var httpStatus=req.status;
if (httpStatus==200 || httpStatus==0){
this.on_load.call(this);
}else{
this.on_error.call(this);
}
}
}
net.ContentLoader.prototype.defaultError=function(){
alert("error fetching data!"
+"\n\nreadyState:"+this.req.readyState
+"\nstatus: "+this.req.status
+"\nheaders: "+this.req.getAllResponseHeaders());
}
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1365651