Ajax实现检验用户名是否存在
一个简单的检查用户名是否存在的功能,可以帮助我们对Ajax的运作原理有深入了解,明白J2EE中的异步通信技术的精华所在。
JSP页面:index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<script type="text/javascript">
//定义变量存放XMLHttpRequest对象
var xmlHttp;
//创建一个XMLHttpRequest对象
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}
}
//启动Ajax异步通信的方法
function beginCheck(){
var tempUsername=document.all.loginName.value;
if(tempUsername==""){
alert("对不起,请输入注册名");
return;
}
//创建一个XMLHttpRequest对象
createXMLHttpRequest();
//将状态触发器绑定到一个函数
xmlHttp.onreadystatechange=processor;
//通过GET方法向指定的URL建立服务器的调用
xmlHttp.open("GET","CheckUser?loginName="+tempUsername);
//发送请求
xmlHttp.send(null);
}
function processor(){
//定义变量存放从服务器返回的响应结果
var responseContext;
if(xmlHttp.readyState==4){//如果响应完成
if(xmlHttp.status==200){//如果返回成功
responseContext=xmlHttp.responseText;
//取出服务器的响应内容
if(responseContext.indexOf("true")!=-1)
alert("恭喜您,可以使用该账号");
else
alert("对不起,该账号已被占用");
}
}
}
</script>
<body>
This is my JSP page. <br>
<form name="form1" action="CheckUser" method="POST">
<input type="text" name="loginName" id="loginName" />
<input type="button" name="checkUsername" value="有效性检查" onclick="beginCheck()" />
</form>
</body>
</html>
配置文件:web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>CheckUser</servlet-name>
<servlet-class>org.CheckUser</servlet-class>
</servlet>
<servlet-mapping>