Ajax异步验证:用户注册


这是一个用户注册的简单演示。用户注册时必须保证用户ID不能重复,那么这种用户检测用户ID的操作就可以用Ajax完成。

异步验证时执行javascript操作:在本程序中,当用户输入完ID后要接着输入注册的其他信息,那么此时利用onBlur()事件,就是当ID输入框丢失焦点时,将用户ID通过Ajax提交到服务器上完成数据验证并返回结果。

OK,大家在网站特别是论坛注册用户时的场景出现了,虽然界面很挫,O(∩_∩)O哈哈~

SQLServer数据库初始化如下:

[java]
//创建表Users
create table Users (userId varchar(30) PRIMARY KEY, name varchar(30), password varchar(32))
//初始化一条用户数据
insert into Users values(‘admin’, ‘administrator’, ‘admin’)
[/java]

下面是代码Demo

regist.html:

[html]
<!DOCTYPE html>
<html>
<head>
<title>regist.html</title>

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<!–<link rel="stylesheet" type="text/css" href="./styles.css">–>

</head>

<body>
<script type="text/javascript">
var xmlHttp;//Ajax核心对象名称
var flag;//定义标志位

function createXMLHttp(){//创建XMLHttpRequest核心对象
if(window.XMLHttpRequest){//判断浏览器类型
xmlHttp = new XMLHttpRequest();
}else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}

function checkUserId(userId){
createXMLHttp();
//设置一个请求,通过地址重写的方式将userId传递到JSP中
xmlHttp.open("POST", "checkServlet?userId=" + userId);
//设置请求完成后处理的回调函数
xmlHttp.onreadystatechange = checkUserIdCallback;
xmlHttp.send(null);
document.getElementById("msg").innerHTML = "正在验证…";
}

function checkUserIdCallback(){//定义回调函数
if(xmlHttp.readyState == 4){//数据返回完毕
if(xmlHttp.status == 200){//HTTP操作正常
var text = xmlHttp.responseText;//接收返回内容
if(text == "true"){//这里接收pw回来的数据
flag = false;//找到了,无法提交注册表单
document.getElementById("msg").innerHTML = "用户ID已存在";
}else{
flag = true;//没找到此用户,可以提交注册表单
document.getElementById("msg").innerHTML = "用户ID可以注册";
}
}
}
}

function checkForm(){
return flag;
}
</script>
<!– 这个表单只演示异步验证,regist.jsp木有写 –>
<form action="regist.jsp" method="post" onSubmit="return checkForm()">
用户名:<input type="text" name="userId" onBlur="checkUserId(this.value)">
<span id="msg"></span>
<br>
姓名:<input type="text" name="name">
<br>
密码:<input type="password" name="password">
<br>
<input type="submit" value="注册">
<input type="reset" value="重置">
</form>
</body>
</html>

[/html]

CheckServlet.java

[java]
package net.singlex.ajax.control;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckServlet extends HttpServlet {

public static final String DBDRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static final String DBURL = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=AjaxUserRegist";
public static final String DBUSER = "sa";
public static final String DBPSW = "123456";

/**
* Constructor of the object.
*/
public CheckServlet() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

this.doPost(request, response);
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("GBK");
response.setContentType("text/html");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
PrintWriter pw = response.getWriter();
String userId = request.getParameter("userId");
try {
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPSW);

String sql = "select count(userId) from Users where userId = ?";//查找输入的ID在数据库中的数量
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);
rs = pstmt.executeQuery();//返回的是一个值,正常情况下如果ID不重复,查询的结果是1
if (rs.next()) {
if (rs.getInt(1)>0) {
pw.print(true);
}else {
pw.print(false);//没查到
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}

[/java]

发表评论