您的位置:首页 > 其它

Ajax 入门程序 -- 检测用户名是否可用

2008-05-18 19:40 357 查看




会员注册唯一性检查是所有会员系统的基本功能之一。在本实例中,使用Ajax技术来实现,业务逻辑放在一个名为CheckUser的servlet中。

页面:

<%@ page language="java" pageEncoding="UTF-8"%>
<%
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>Ajax技术体验</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>

<body>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}
}
function beginCheck(){
var tempLoginName = document.all.loginName.value;
if(tempLoginName==""){
alert("请输入用户名!");
return;
}
createXMLHttpRequest();
xmlHttp.onreadystatechange = processor;
xmlHttp.open("GET","CheckUser?loginName="+tempLoginName);
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>

<form action="CheckUser" method="post">
用户名:<input name="loginName" type="text">
<input type="button" name="checkLoginName" value="检测用户名是否可用" onclick="beginCheck()">
</form>
</body>
</html>

CheckUser.java

package test;

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 CheckUser extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String [] logined = {"admin","user","test","张三"};
String loginName = request.getParameter("loginName");
String responseContext = "true";
for(int i=0; i<logined.length;i++){
if(loginName.equals(logined[i])){
responseContext = "false";
}
}
out.println(responseContext);
out.flush();
out.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: