<%@ page language="java" import="java.util.*" 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>My JSP 'regUser.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"> <script type="text/javascript"> var xhr; //创建Xhr对象的函数; function createXhr(){ try{ //普通方式; return new XMLHttpRequest(); }catch(e){ //异常,则另外一种方式; return new ActiveXObject("Microsoft.XMLHTTP"); } } //用户名,文本框失去焦点处理函数; function checkUser(){ xhr=createXhr(); //得到文本框中输入的内容; var username=document.getElementById("username").value; //设置回调函数; xhr.onreadystatechange=callback; //alert(username); //设置请求方式和url,因为是get方式,请求数据直接在url的后面; xhr.open("get","checkUserAction?username="+username); //发送请求; xhr.send(null); } function callback(){ //判断请求完成,并且成功返回; if(xhr.readyState==4&&xhr.status==200){ var msg=document.getElementById("msg"); var res=xhr.responseText; //alert(res); //根据响应返回的数据,进行页面更新; if(res=="true"){ msg.innerHTML='用户名已经存在'; }else{ msg.innerHTML='用户名可以注册'; } } } </script> </head> <body> <form action="regAction" method="post"> 账户:<input type='text' id='username' name='username' onblur='checkUser()'/><span id='msg'></span><br/> 密码:<input type='password' name='userpwd'><br/> 邮箱:<input type='text' name='email'><br/> 地址:<input type='text' name='address'><br/> <input type='submit' value='注册'/> </form> </body> </html>
响应的Servlet代码:
package web; 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 CheckUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter out=resp.getWriter(); //获取提交数据; String username=req.getParameter("username"); if("admin".equals(username)){ out.print("true"); }else{ out.print("false"); } out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }