index.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>ajax</title>
<script type="text/javascript">
var xmlHttp; // 局部刷新的关键,通过这个对象与服务器连接
// 实例化xmlHttp,根据不同的浏览器获得xmlHttp对象
function init(){
try{
xmlHttp=new ActiveXObject('Msxml2.XMLHTTP');
}catch(e){
try{
xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');
}catch(e){
try{
xmlHttp=new XMLHttpRequest();
}catch(e){}
}
}
}
// 调用此方法与服务器互动
function ajax(name){
init(); // 把请求传递给ajax引擎,需要先获得xmlHttp对象
if(name.length==0){
document.getElementById("divname").innerHTML="必须输入用户名";
document.getElementById("name").focus();
return;
}
var url="ajax?name="+name+"&&date="+Date(); // 向servlet传递参数
xmlHttp.open("get",url,true); // 向servlet传递参数,设置传递模式和url
xmlHttp.onreadystatechange = handleCheckName; // 设置回调方法为handleCheckName,明确当xmlHttp工作状态发生改变时的操作
xmlHttp.send(null); // ajax引擎真正发送请求
}
// 实现回调方法,实现信息显示
function handleCheckName(){
// 首先判断工作状态,只有工作完成,才来处理结果
if(xmlHttp.readyState==4){
// 判断http状态码,获得处理结果是否正常的信息
if(xmlHttp.status==200){
// xmlHttp.responseText为服务器返回的数据
if(xmlHttp.responseText=="1"){
document.getElementById("divname").innerHTML="对不起,用户已存在!";
document.getElementById("divname").style.color="black";
}
if(xmlHttp.responseText=="2"){
document.getElementById("divname").innerHTML="用户名只能是3-10位字母,数字";
document.getElementById("divname").style.color="black";
}
if(xmlHttp.responseText=="3"){
document.getElementById("divname").innerHTML="恭喜你,用户名可以继续注册!";
document.getElementById("divname").style.color="red";
}
}
}
}
</script>
</head>
<body>
<input type="text" name="name" οnkeyup="ajax(this.value);" />
<div id="divname"></div>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>ReturnName</servlet-name>
<servlet-class>ajax.servlet.ReturnName</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReturnName</servlet-name>
<url-pattern>/ajax</url-pattern>
</servlet-mapping>
</web-app>
ReturnName.java
package ajax.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ReturnName extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
int a=0;
if (name.equals("abc")) {
a=1;
} else if (!name.matches("[a-zA-Z0-9]{3,10}")) {
a=2;
} else {
a=3;
}
response.getWriter().print(a);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}