这是一个比较简单的验证,分为两部分,界面层用jsp,请求转发层用到的是Servlet
JSP部分代码如下
<script type="text/javascript">
// 首先创建一个xmlHttpReq对象,非IE浏览器使用new XMLHttpRequest()
var xmlHttpReq;
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttpReq = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}else{
xmlHttpReq = new XMLHttpRequest();
}
}
//这是表单验证触发函数
function check(){
createXMLHttpRequest();
var username =document.getElementById("username").value;
//将用户id传给一个Servlet
var url="CheckUser?username="+username;
//采用Get的请求方式
xmlHttpReq.open("GET",url,true);
xmlHttpReq.onreadystatechange = showResult;
//onreadystatechange的值改变时触发的showResult函数
xmlHttpReq.send();
}
//返回响应信息,并显示在一个DIV中
function showResult(){
if(xmlHttpReq.readyState == 4){
if(xmlHttpReq.status == 200){
//将响应信息作为字符串返回
var result = xmlHttpReq.responseText;
alert(result);
document.getElementById("checkResult").innerHTML="<b>"+result+"</b>"; }
}
}
</script>
姓名:
<input type="text" id="username" οnblur="check()">
<span id="checkResult" style="float:left;color: red"></span>
Servlet部分的代码如下
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String userName=request.getParameter("username");
PrintWriter out = response.getWriter();
out.print(userName);
//此部分内容可以结合数据库进行处理
if(userName.equals("javayang")){
out.print("此用户已经存在");
}else{
out.print("可以注册");
}
out.flush();
out.close();
}
web.xml中的配置如下
<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>com.my.action.CheckUser</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckUser</servlet-name>
<url-pattern>/CheckUser</url-pattern>
</servlet-mapping>