今天做登录/注册系统的时候需要验证用户名是否已被注册,用表单提交然后servlet判断会刷新一下,原来的已填写的数据不会保存以及用户体验差,查了一下发现Ajax可以实现。
1.在script里创建一个参数和三个function
function createXMLHttpRequest():因为IE浏览器的xmlHttp不一样,因此判断浏览器类型之后再创建xmlHttp.
function validate(username):将用户名传入打开的Servlet,并对其判断。
function callback():xmlHttp发送出去后返回的值交给这个函数处理。
var xmlHttp;
function createXMLHttpRequest() {
//表示当前浏览器不是ie,如ns,firefox
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validate(username) {
//alert(username);
createXMLHttpRequest();
//设置请求方式为GET,设置请求的URL,设置为异步提交
//alert(url);
xmlHttp.open("Get","UsernameValidate?username="+username,true);
//将方法地址复制给onreadystatechange属性
xmlHttp.onreadystatechange=callback;
//将设置信息发送到Ajax引擎
xmlHttp.send(null);
}
//发送请求之后,返回的状体
function callback() {
//Ajax引擎状态为成功
if (xmlHttp.readyState == 4) {
//HTTP协议状态为成功
if (xmlHttp.status == 200) {
var text=xmlHttp.responseText;
if(text=="true\n")
$("info").innerHTML="该用户已经被注册";
else
$("info").innerHTML="";
}else {
alert("请求失败,错误码=" + xmlHttp.status);
}
}
}
(PS:不知道为什么text里就是多了一个回车,因此我就在判断里也加了回车)(解答:因为我在servlet的是out.println("true"),因此多了回车,改成out.print("true")即可。
2.文本框调用
<span id="info" style="color:red"></span>
<form id="form" action="Register" method="post">
onblur指在元素失去焦点时做的处理。昵称:<input type="text" id="name"name="name" maxlength="20" οnblur="validate(this.value)">
3.判断是否重复的servlet
package com.zhoudq.servlet.user; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zhoudq.dao.PojoDAOImpl; import com.zhoudq.pojo.User; @WebServlet(urlPatterns="/UsernameValidate") public class UsernameValidate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { System.out.println("UV-Servlet"); PrintWriter out=response.getWriter(); try { String username=request.getParameter("username"); ApplicationContext context=new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml"}); PojoDAOImpl dao=(PojoDAOImpl)context.getBean("pojodao"); List<User> get=dao.find("from User u where u.username='"+username+"'"); if(get.size()>0) { //has been registered System.out.println("true"); out.print("true"); }else { //has not been registered System.out.println("false"); out.print("false"); } }catch(Exception e) { e.printStackTrace(); } } }
4.效果