[ ajax註冊驗證 ]

來源:互聯網
上載者:User

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>

這就是全部了!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.