使用Ajax验证用户名

Ajax是一项很重要的技术,下面简要举个例子,来解释如何使用Ajax。步骤如下:
使用Ajax验证用户名
使用文本框的onBlur事件

使用Ajax技术实现异步交互
创建XMLHttpRequest对象
通过 XMLHttpRequest对象设置请求信息
向服务器发送请求
创建回调函数,根据响应状态动态更新页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>异步验证用户名</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
  <table>
  <tr>
  <td>用户名:</td>
    <td><input type="text" name="username" id="name" onblur="change()"/></td>
    <td><span style="display: none;color: red" id="span"></span></td>
  </tr>
    <tr>
    <td>密码</td>
    <td><input type="password" name="pwd" id="password" /></td>
    </tr>
        <tr>
   
    <td><input type="button" value="提交" onclick="change()"></td>
        </tr>
  
  </table>


  </body>
  <script type="text/javascript">
  //使用异步刷新技术实现验证用户名
  
  //声明全局对象
  var xmlhttp;
  //第一步:创建ck对象
  function ck(){
      if(window.XMLHttpRequest){
          xmlhttp=new XMLHttpRequest;
      }else if(window.ActiveObject){
          xmlhttp=new ActiveObject("Microsoft.XMLHTTP")
      }
      
  }
  
  //第二步:响应鼠标事件
  function change(){
      //获取用户名
      var username=document.getElementById("name");
      var password = document.getElementById("password");

      if(!username.value){
          alert("用户名不能为空");
      }else if(!password.value){
              alert("密码不能为空!!!")
              
              }else{
               
    
          //请求异步刷新;以请求地址作为参数传递
          doAjax("select/doselect?username="+username.value+"password="+password.value);
      }
  }
  //第三步:获取URL
  function doAjax(url){
      //初始化ck;
          ck();
          //判断对象是否初始化成功
          if(xmlhttp!=null){
              //如果不为空,则说明初始化成功
              //开始请求服务器
              xmlhttp.open("post",url,true);//初始化请求参数
              xmlhttp.onreadystatechange=ok;//指定回调函数
              xmlhttp.send(null);
              
          }else{
              alert("xmlhttp初始化失败!!!");
          }
    }
  //指定回调函数
  function ok(){
      //判断响应状态
      if(xmlhttp.readyState==4){
          if(xmlhttp.status==200){
              chuli(xmlhttp.responseText);
          }
      }
      
  }
  function chuli(status){
      var span=document.getElementById("span");
      span.innerHTML=status;
      span.style.display="block";
      
  }
  
  
  </script>
</html>

JAVA代码Servlet语法:

javapackage select;



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 doselect extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public doselect() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("请求正常");
        
        
        String[] user = new String[]{"胖胖","薇薇","黄鼠狼","李四"};

        
        String status = "用户名可以使用!";//状态:如果为0则表示该用户名不存在;否则用户名已占用

        
        //得到请求参数
        String name = request.getParameter("username");
        name = new String(name.getBytes("ISO-8859-1"),"GBK");


        
        for (int i = 0; i < user.length; i++) {
            if(name.equals(user[i])){
                status = "用户名已存在!";
            }
        }
        
        //将信息返回客户端
        response.setContentType("text/html");
        response.setCharacterEncoding("GBK");
        PrintWriter out = response.getWriter();
        out.println(status);
    
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    

 

在Java_Web项目的xml文档配置具体路径

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    
      <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>doselect</servlet-name>
    <servlet-class>select.doselect</servlet-class>
  </servlet>



  <servlet-mapping>
    <servlet-name>doselect</servlet-name>
    <url-pattern>/select/doselect</url-pattern>
  </servlet-mapping>
  


<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

posted on 2015-05-31 11:08  梦之航  阅读(1871)  评论(0编辑  收藏  举报

导航