[ ajax注册验证 ]

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>

这就是全部了!

你可能感兴趣的:(java,jquery,Ajax,servlet,IE)