1. 程式人生 > >驗證碼無重新整理驗證(AJAX技術)

驗證碼無重新整理驗證(AJAX技術)

看了兩天也沒明白為何這程式碼不能實現“接連3次輸入錯誤,更新驗證碼,重新輸入”的功能,阿西吧等我再研究一哈回來更改。

需要生成驗證碼圖片模板的小夥伴們看過來~(微笑臉)

執行效果示意:


主頁面 img.jsp

<%@ page language="java" contentType="text/html; charset=GBK" import="java.sql.*" errorPage="" pageEncoding="GBK"%>
<%
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(無重新整理及時提示)驗證碼例項 code by TX
<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;
	}
}
%>
<script type="text/javascript">
var times = 0;
function subform()
{
	var gtext = this.req.responseText;
	//out.println(gtext);
	var info = document.getElementById("info");
	//info.innerHTML = "111";
	if(gText.indexOf("validate_successful") != -1)
	{
		//info.innerHTML = "<font color = green>驗證碼通過</font>";
		document.forms["myform"].submit();
	}
	else
	{
		times++;
		if(times >= 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)) //匹配0個或多個空白符,空白符包括空格、換行、製表等符號。
	{
		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;
}
</script>
<form action = "img.jsp" name = "myform" method = "post" onsubmit = "return validata(this);">
<table>
<tr><th>您的姓名:</th><th><input type = "text" name = "name" size = 10></th></tr>
<tr><th>驗證碼:</th><th><input type = "text" name = "num" size = 10 maxlength = "4"></th>
<th><img src = "random.jsp" id = "random" align = "" valign = "absmiddle" hspace = "5"></th>
<th><a href = "javascript:show(document.getElementById('random'))">驗證碼看不清</a></th></tr>
<tr><th><input type = "submit" value = "提交"></th></tr>
</table>
<div id=info style="color:red;padding:10px;font-size:12px;"></div>
</form>
</body>
</html>
反饋xmlhttp請求的頁面 num.jsp
<%@ page language="java" contentType="text/html; charset=GBK" import="java.sql.*" errorPage = "" pageEncoding="GBK"%>
<%
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
response.setContentType("text/html; charset=GBK");
%>
<%
String num = request.getParameter("num");
String random = (String)session.getAttribute("random");
//out.print("num:" +num);
//out.print("random:" +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);
	}
}
%>

生成驗證碼圖片的頁面 random.jsp 

<%@ page autoFlush = "false" import = "java.util.*,java.awt.*,java.awt.image.*,com.sun.image.codec.jpeg.*,java.util.*"%>
<%request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
response.setContentType("text/html; charset = GBK");
%>
<%
String chose = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ";
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, 20);
g.dispose();
ServletOutputStream outStream = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
encoder.encode(image);
outStream.close();
%>

封裝xmlhttp物件,封裝的目的是可以很方便地呼叫,例如封裝為 net.js。

/* namespacing object*/
var net = new Object();

net.READY_STATE_UNINITIALIZED = 0;
net.READY_STATE_LOADING = 1;
net.READY_STATE_LOADED = 2;
net.READY_STATE_INTERACTICE = 3;
net.READY_STATE_COMPLETE = 4;

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)
	{
		try{
			this.req = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(el){
			try{
				this.req = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e2){}
		}
	}
	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.getAllReaponseHeaders());
}