上篇文章討論了Ajax技術的理論,本篇文章討論的是實際編程中如何利用XMLHttpRequest非同步地向伺服器發送get請求,並且不考慮中文問題,中文亂碼問題在後續文章中討論!這裡以一個表單註冊過程為例講解Ajax的過程,為簡單起見,使用者名稱並沒有到實際資料庫裡做查詢驗證,這裡只簡單地認為只要使用者名稱為"tom",即表示已經註冊過,必須重新換一個使用者名稱。使用者名稱文字框的焦點一旦失去,Ajax就開始發送請求。
先看樣本工程的檔案目錄結構:
register.jsp :
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script>function getXmlHttpRequest(){var xhr=null;if((typeof XMLHttpRequest)!='undefined'){xhr=new XMLHttpRequest();}else{xhr=new ActiveXObject("Microsoft.XMLHttp");}return xhr;}function valiUsername(){var xhr=getXmlHttpRequest();xhr.onreadystatechange=function(){if(xhr.readyState==4){if(xhr.status==200){var doc=xhr.responseText;document.getElementById('username_msg').innerHTML=doc;}else{document.getElementById('username_msg').innerHTML='sorry,system error...';}}else{document.getElementById('username_msg').innerHTML='checking...';}}var url="valiusername.do?username="+document.getElementById('n1').value;xhr.open("get",url,true);xhr.send(null);}</script></head><body><form action="register.do" method="post">username:<input type="text" name="username" id="n1" onblur="valiUsername();"><span style="color:red" id="username_msg"></span><br>password:<input type="password" name="password"><br><input type="submit" value="register"></form></body></html>
login.jsp :
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><form action="login.do" method="post">username:<input type="text" name="username"><br>password:<input type="password" name="password"><br><input type="submit" value="login"></form></body></html>
web.xml :
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>UsernameServlet</servlet-name> <servlet-class>web.UsernameServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UsernameServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
UsernameServlet.java :
public class UsernameServlet extends HttpServlet {public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String uri=request.getRequestURI();String path=uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));PrintWriter pw=response.getWriter();if(path.equals("/valiusername")){String username=request.getParameter("username");if(username.equals("tom")){pw.println("username exists,change one...");}else{pw.println("OK");}}if(path.equals("/register")){String username=request.getParameter("username");String password=request.getParameter("password");response.sendRedirect("login.jsp");}}}