1.用戶端:JSP
<%@ page language="java" pageEncoding="GBK"%><html><head><title>index.jsp</title></head><mce:script type="text/javascript"><!--var xhr = false;function checkUserName(){//1.建立XMLHttpRequest對象;//IE Browser:try{ xhr = new ActiveXObject("Microsoft.XMLHTTP");}catch(e){try{xhr = new ActiveXObject("Msxml2.XMLHTTP");}catch(e){xhr = false;}}if(!xhr&&typeof XMLHttpRequest!="undefined"){xhr = new XMLHttpRequest();}//2.發出請求:var url ="serverPort?username="+escape(document.userForm.elements("name").value);xhr.open("POST",url,true);xhr.onreadystatechange = process;xhr.send(null);}function process(){if(xhr.readyState == 4){if(xhr.status == 200){document.getElementById("userSpan").innerHTML = xhr.responseText;}}}// --></mce:script><body><form action="" method="post" name="userForm"><table><caption>使用者註冊!</caption><tr><td>使用者名稱:</td><td><input type="text" name="name" onblur="checkUserName()"><span id="userSpan">*</span></td></tr><tr><td>密碼:</td><td><input type="password" name="password" ></td></tr></table></form></body></html>
2.服務端:Servlet
package servlet;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 ServerPort extends HttpServlet{private static final long serialVersionUID = 1L;public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html;charset=GBK");String userName = request.getParameter("username");PrintWriter out = response.getWriter();if(userName.trim().length()==0||userName==null){out.println("<font color='red'>使用者名稱不可為空!</font>");}else if("neyjar".equals(userName)){out.println("<font color='red'>使用者已存在!</font>");}else{out.println("<font color='blue'>可以使用此使用者名稱!</font>");}}public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}}
3.web.xml中配置那個Servlet:
<servlet> <servlet-name>servletPort</servlet-name> <servlet-class>servlet.ServerPort</servlet-class> </servlet> <servlet-mapping> <servlet-name>servletPort</servlet-name> <url-pattern>/serverPort</url-pattern> </servlet-mapping>
這就是全部了!