0

我有一个 html 注册表单,我正在使用 Javascript 检查字段以进行验证。但是,我需要检查用户名是否存在于数据库中,如果它确实在警告用户名被使用的部分中打印出一条消息。但是,我必须查看用户是否存在的检查不起作用。

我尝试检查用户名是否存在于用户类中。我正在尝试进行实时验证,因此当用户输入用户名时,我有一个 if 语句来检查数据库以查看用户名是否存在于数据库中。我一直在寻找解决方案,我在网上只能找到使用 php 的解决方案。我想知道有人可以帮助或建议我。我已经包含了表单、servlet、使用的 ajax、用户类和 servlet。- 对不起所有的代码,但我希望有人能看到我哪里出错了。

HTML 表格

     Username:

     <input id="username" required type="text" name="username" placeholder="Username"  autocomplete="off" onkeyup="updateOutput(this.value)" />
<div id="userNameMessage"></div>
</p>  

小服务程序

    public boolean SaveUser() { 

    boolean saved = false;
    try {


        Connection connection = DBHelperClass.getConnection();
        Statement statement = connection.createStatement();

        String userCheck ="SELECT * FROM User where username='" + userName + "'";

        ResultSet rs1 = statement.executeQuery(userCheck);
        boolean userExists = rs1.next();

                 if (userExists){

        String template = "INSERT INTO user(userName, password, firstName,secondName, email, address, mobile,image) "
                + "VALUES (?,?,?,?,?,?,?,?)";

        PreparedStatement inserter = connection.prepareStatement(template);
        inserter.setString(1, this.userName);
        inserter.setString(2, this.password);
        inserter.setString(3, this.firstName);
        inserter.setString(4, this.secondName);
        inserter.setString(5, this.email);
        inserter.setString(6, this.address);
        inserter.setString(7, this.mobile);
        inserter.setString(8, this.image);

        inserter.executeUpdate();

        ResultSet rs = statement.executeQuery("select max(userid) from user");
        while (rs.next()) {
            System.out.println("max row " + rs.getString(1));
            this.userId = rs.getString(1);
        }


        saved = true;
        inserter.close();
         }
                 else{
                // print message on html page
                 }
        connection.close();



    } catch (SQLException ex) {
        Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
    }



    return saved;
}

小服务程序

*/ else if (option.equalsIgnoreCase("add")) {


            String username = mrequest.getParameter("username");
            System.out.println("username" + username);


            String password = mrequest.getParameter("password");
            System.out.println("password" + password);

            String firstName = mrequest.getParameter("firstName");
            System.out.println("firstName" + firstName);


            String secondName = mrequest.getParameter("secondName");
            System.out.println("secondName" + secondName);

            String email = mrequest.getParameter("email");
            System.out.println("email" + email);


            String add = mrequest.getParameter("address");
            System.out.println("address" + address);

            String mobile = mrequest.getParameter("mobile");
            System.out.println("mobile" + mobile);

            String image = mrequest.getParameter("image");

            String userRole = null;


            u = new User(null, username, password, firstName, secondName, email, add, mobile, filename, null);
            boolean saved = u.SaveUser();
            session.setAttribute("user", u);
            address = "/login.html";

AJAX 代码

         *
       var xmlHttp;  
       function updateOutput(inputString)        {               

   if(inputString.length == 0)            {                

      document.getElementById("output").innerHTML = "";                             
    return;            
      }                       
      try            {                
     if(window.XMLHttpRequest)                    
    xmlHttp = new XMLHttpRequest();                
      else if (window.ActiveXObject)                   
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                                                
      if(!xmlHttp || xmlHttp == null)                {                    
       return;                }                                
       var url="doajaxstuff.aspx?q=" + inputString;                
        xmlHttp.onreadystatechange=StateChanged;                
     xmlHttp.open("GET", url, true);               
     xmlHttp.send(null);            }            
         catch(e)            {                
         document.getElementById("output").innerHTML = "An error occured";           
             }                   }                function StateChanged()        {            
             if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))            {                
             document.getElementById("output").innerHTML = xmlHttp.responseText;                   
             }                }    
             </script>
4

1 回答 1

0

我为您创建了示例示例。这应该会有所帮助。

AJAX 调用:

<script type="text/javascript">

    var xmlHttp;

    function updateOutput(inputString) {
        if (inputString.length == 0) {
            document.getElementById("output").innerHTML = "";
            return;
        }
        try {
            if (window.XMLHttpRequest)
                xmlHttp = new XMLHttpRequest();
            else if (window.ActiveXObject)
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            if (!xmlHttp || xmlHttp == null) {
                return;
            }
            var url = "validate?userName=" + inputString; // Here, I have mapped servlet as "validate".
            xmlHttp.onreadystatechange = StateChanged;
            xmlHttp.open("GET", url, true);
            xmlHttp.send(null);
        } catch (e) {
            document.getElementById("userNameMessage").innerHTML = "An error occured";
        }
    }
    function StateChanged() {
        if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
            document.getElementById("userNameMessage").innerHTML = xmlHttp.responseText;
        }
    }
</script>

HTML:

Username:  <input id="username" type="text" name="userName"  onblur="updateOutput(this.value)" />
<span id="userNameMessage" style="margin-left:10px;"></span></br>
First Name: <input id="firstname" type="text" name="firstName"  />
.... other fields

小服务程序:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String strStatus = "Username is available";
        try{
            System.out.println("Performing check");
            String username = request.getParameter("userName");
            String strQuery = "SELECT * FROM users WHERE uname='" + username +"'";
            ResultSet rs = DatabaseManager.executeQuery(strQuery);
            boolean userExists = rs.next();
            if (userExists){
                strStatus = "Username already exists"; // Return Exist Msg
            }
        }catch(Exception e){
            strStatus = "Some error occured. Try again"; // Return Err Msg
            e.printStackTrace();
        }
        out.println(strStatus);
    }

现在,jQuery Ajax 调用被认为是一种很好的做法。你可以看看这里

于 2013-03-07T05:54:23.993 回答