<form id="registerForm" action="" method="post"onsubmit="return checkForm();">
用户名: <input type="text" id="username" name="username" maxlength="20" onblur="checkUsername()"/><span id="span1"></span>
密码: <input type="password" id="password" name="password" maxlength="20"/>
确认密码: <input id="repassword" type="password" name="repassword" maxlength="20"/>
<input type="submit" value="注册">
</form>
function checkForm(){
// 校验用户名:
// 获得用户名文本框的值:
var username = document.getElementById("username").value;
if(username == null || username == ''){
alert("用户名不能为空!");
return false;
}
// 校验密码:
// 获得密码框的值:
var password = document.getElementById("password").value;
if(password == null || password == ''){
alert("密码不能为空!");
return false;
}
// 校验确认密码:
var repassword = document.getElementById("repassword").value;
if(repassword != password){
alert("两次密码输入不一致!");
return false;
}
}
function checkUsername(){
// 获得文件框值:
var username = document.getElementById("username").value;
// 1.创建异步交互对象
var xhr = createXmlHttp();
// 2.设置监听
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
document.getElementById("span1").innerHTML = xhr.responseText;
}
}
}
// 3.打开连接
xhr.open("GET","${pageContext.request.contextPath}/user_findByName.action?time="+new Date().getTime()+"&username="+username,true);
// 4.发送
xhr.send(null);
}
function createXmlHttp(){
var xmlHttp;
try{ // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
try{// Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){}
}
}
return xmlHttp;
}
public String findByName() throws IOException {
// 调用Service进行查询:
User existUser = userService.findByUsername(user.getUsername());
// 获得response对象,项页面输出:
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
// 判断
if (existUser != null) {
// 查询到该用户:用户名已经存在
response.getWriter().println("<font color='red'>用户名已经存在</font>");
} else {
// 没查询到该用户:用户名可以使用
response.getWriter().println("<font color='green'>用户名可以使用</font>");
}
return NONE;
}