在jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gbk">
<title>请注册</title>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript">
var xhr=null;
function checkUname(){
var username=document.myform.uname.value;
//alert(username);
if(username==""||username==null){
document.getElementById("msgDiv").innerHTML="<font color='red'>请输入用户名</font>";
}
//ajax的核心对象
//var xhr=new XMLHttpRequest();//只对非ie浏览器生效
if(window.ActiveXObject){
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}else{
xhr=new XMLHttpRequest();
}
var url="http://localhost:8080/12softsms0415/RegServlet?uname="+username;
//当核心对象的状态发生改变,它的处理函数
xhr.onreadystatechange=haolejiaowo;
xhr.open("get",url,true);
xhr.send(null);
}
//才是核心处理函数
function haolejiaowo(){
if(xhr.readyState==4&&xhr.status==200){
var result=xhr.responseText;//得到远程服务器返回的结果
if(result.indexOf("true")!=-1){
document.getElementById("msgDiv").innerHTML="<font color='red'>用户名已存在</font>";;
}else{
document.getElementById("msgDiv").innerHTML="可以注册";
}
}
}
</script>
</head>
<body>
<div align="center">
<%-- 登录 --%>
<div class="login" align="center">
<br/>
<h2>账号注册</h2>
<form action="UserServlet" method="post" name="myform">
<input type="hidden" name="cmd" value="reg">
用户名<input type="text" name="uname" class="input" οnblur="checkUname()"/>
<div id="msgDiv" style="display:inline"></div>
<br/>
密 码<input type="password" name="upass" class="input"/><br/>
重复密码<input type="password" name="upassrep" class="input"/><br/>
<input type="submit" value=" 注册 " class="btn"/>
</form>
</div>
</div>
</body>
</html>
再写一个servlet测试,以固定的账号进行测试:
package com.neusoft.sms.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegServlet extends HttpServlet {
public boolean isExist(String username){
//模拟后台数据库有三个用户
String[] names={"12210810226","吕梁锋","尼玛"};
for (String s : names) {
if(username.equalsIgnoreCase(s)){
return true;
}
}
return false;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
String username=request.getParameter("uname");
boolean flag=isExist(username);
out.println(flag);
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}}
然后进行注册测试: