本文内容摘自:《Java Web开发教程——入门与提高篇(JSP+Servlet)》
下面以注册过程中用户名是否存在的验证为例介绍AJAX
的应用。
功能描述:用户注册的用户名不允许重复,所以在用户提交时候需要判断。为了让用户早知道结果,在用户输入用户名之后就应该进行判断,可以采用AJAX
进行处理。
假设:为了简化代码,该实例的验证过程不使用数据库,并且也不使用专门的JavaBean
,直接在Servlet
中验证,假设已有用户“zhangsan
”、“lisi
”和“wangwu
”。
实例包含两个文件:
l
界面文件;
l
服务器端处理文件。
注册界面的代码如下
:
<%@ page language="java" pageEncoding="gb2312"%>
<%
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 'register.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 language="javaScript">
var xMLHttpRequest=false;
function createXMLHttpRequest(){
if(window.XMLHttpRequest){ // Mozilla
浏览器
xMLHttpRequest = new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
xMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xMLHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
}
function processResponse(){
if(xMLHttpRequest.readystate==4){ //
判断对象状态
if(xMLHttpRequest.status==200){ //
信息已经返回,开始处理信息
var res = xMLHttpRequest.responseText;
//window.alert(res);
document.getElementById("userlabel").innerText=res;
}else{ //
页面不正常
window.alert("
您所请求的页面有异常!
");
}
}
}
function usercheck(){
createXMLHttpRequest();
xMLHttpRequest.open("GET","check?username="+document.registerform.username.value,true);
xMLHttpRequest.onreadystatechange=processResponse; //
指定响应函数
xMLHttpRequest.send(null); //
发送请求
}
</script>
<body>
<form name="registerform" action="register" method="post">
<P>
注册
</P><P>
用户名:
<input type="text" name="username" onClick="usercheck()"><label for=username id="userlabel">
不能为空
</label></P><P>
性别:
<input type="radio" checked="checked" value="
男
" name="sex">
男
<input type="radio" value="
女
" name="sex">
女
</P><p> <input type="submit" value="
注册
"></p></form>
</body>
</html>
服务器端的主要代码如下(Servlet
的部分代码):
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
String username = request.getParameter("username");
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
if(username.equals("zhangsan")
||username.equals("lisi")
||username.equals("wangwu")){
out.println("
用户名已经被占用!
");
}else
{
out.println("
用户名可以使用!
");
}
out.flush();
out.close();
}
下一讲:JavaBean