<%@page pageEncoding="utf-8" contentType="text/html;charset=utf-8"%> <html> <head> <script type="text/javascript"> //step1 获得XmlHttpRequest对象。 function getXmlHttpRequest(){ var xmlHttpRequest = null; if ((typeof XMLHttpRequest) != 'undefined') { xmlHttpRequest = new XMLHttpRequest(); } else { xmlHttpRequest = new ActiveXObject('Microsoft.XMLHttp'); } return xmlHttpRequest; } function valiusername(){ //step1 获得XmlHttpRequest对象。 var xhr = getXmlHttpRequest(); var value = document.getElementById("username").value; //step2 使用XmlHttpRequest对象向服务器发送请求。发送get请求 xhr.open("get","valiusername.do?username=" + encodeURI(value),true); //step4 使用服务器返回的数据更新页面。 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ var txt = xhr.responseText; var obj = document.getElementById('username_msg'); obj.innerHTML = txt; }else{ var obj = document.getElementById('username_msg'); obj.innerHTML = 'system error'; } }else{ var obj = document.getElementById('username_msg'); obj.innerHTML = 'checking...'; } }; xhr.send(null); } function valiusername2(){ var xhr = getXmlHttpRequest(); var value = document.getElementById("username").value; xhr.open("post","valiusername.do",true); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ var txt = xhr.responseText; var obj = document.getElementById('username_msg'); obj.innerHTML = txt; }else{ var obj = document.getElementById('username_msg'); obj.innerHTML = 'system error'; } }else{ var obj = document.getElementById('username_msg'); obj.innerHTML = 'checking...'; } }; xhr.send("username=" + value); } </script> </head> <body style="font-size:30px;"> <form action="regist.do" method="post"> 用户名:<input id="username" name="username" onblur="valiusername();"/> <span style="color:red;" id="username_msg"></span> <br/> 密码:<input name="pwd"/> <br/> <input type="submit" value="确认"/> </form> </body> </html>
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 UserServlet extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { request.setCharacterEncoding("utf-8"); String uri =request.getRequestURI(); String path = uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf(".")); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); if(path.equals("/valiusername")){ System.out.println("valiusername..."); String username = request.getParameter("username"); System.out.println("username:" + username); if(username.equals("张三")){ out.println("用户名已经存在."); }else{ out.println("可以使用"); } }else if(path.equals("/regist")){ } } }