使用Ajax连接数据库?

使用Ajax连接数据库?,ajax,jsp,Ajax,Jsp,我想使用Ajax进行用户ID验证,有人能帮我连接数据库吗 这是我的JSP页面。 在这里输入代码 <script type="text/javascript"> /* * creates a new XMLHttpRequest object which is the backbone of AJAX, * or returns false if the browser doesn't support it */ function getXML

我想使用Ajax进行用户ID验证,有人能帮我连接数据库吗

这是我的JSP页面。 在这里输入代码

   <script type="text/javascript">

    /* 
   * creates a new XMLHttpRequest object which is the backbone of AJAX, 
  * or returns false if the browser doesn't support it 
  */
   function getXMLHttpRequest() { 
   var xmlHttpReq = false; 
   // to create XMLHttpRequest object in non-Microsoft browsers 
    if (window.XMLHttpRequest) { 
      xmlHttpReq = new XMLHttpRequest(); 
     } else if (window.ActiveXObject) { 
     try { 
      // to create XMLHttpRequest object in later versions 
      // of Internet Explorer 
      xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP"); 
     } catch (exp1) { 
       try { 
        // to create XMLHttpRequest object in older versions 
        // of Internet Explorer 
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); 
       } catch (exp2) { 
         xmlHttpReq = false; 
       } 
    } 
   } 
   return xmlHttpReq; 
   } 
  /* 
  * AJAX call starts with this function 
   */
  function makeRequest() 
  { 

 var c=document.getElementById("userid").value;
     var xmlHttpRequest = getXMLHttpRequest(); 
    xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest); 
   xmlHttpRequest.open("POST", "../userid", true); 
   xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-   urlencoded");   
   xmlHttpRequest.send("requestType=ajax&userid="+c); 
    } 

   /* 
   * Returns a function that waits for the state change in XMLHttpRequest 
   */
 function getReadyStateHandler(xmlHttpRequest) { 

   // an anonymous function returned 
   // it listens to the XMLHttpRequest instance 
   return function() { 
    if (xmlHttpRequest.readyState == 4) { 
     if (xmlHttpRequest.status == 200) { 
     document.getElementById("print").innerHTML = xmlHttpRequest.responseText; 
     } else { 
     alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText); 
     } 
    } 
  }; 
 }


    <form  action="<%=application.getContextPath() %>/Login"  method="post"      name="myForm">

  <table>
   <tr>
  <td>UserId</td>
  <td><input type="text" name="userid" id="userid" onblur="makeRequest()" > </td>
   </tr>

   <tr>
   <td>Password</td>
   <td><input type="password" name="password" > </td>
   </tr>

   <tr><td></td>
    <td><input type="submit" name="submit" value="Submit"></td>
   <td><input type="hidden" name="requestType" value="Login"> </td>
  </tr>

  </table>
 </form>
   </script>

/* 
*创建一个新的XMLHttpRequest对象,它是AJAX的主干,
*如果浏览器不支持,则返回false
*/
函数getXMLHttpRequest(){
var xmlHttpReq=false;
//在非Microsoft浏览器中创建XMLHttpRequest对象
如果(window.XMLHttpRequest){
XMLHttpRequest=新的XMLHttpRequest();
}如果(window.ActiveXObject){
试试{
//在更高版本中创建XMLHttpRequest对象
//Internet Explorer的应用
xmlHttpReq=新的ActiveXObject(“Msxml2.XMLHTTP”);
}捕获(exp1){
试试{
//在旧版本中创建XMLHttpRequest对象
//Internet Explorer的应用
xmlHttpReq=新的ActiveXObject(“Microsoft.XMLHTTP”);
}捕获(exp2){
xmlHttpReq=false;
} 
} 
} 
返回xmlHttpReq;
} 
/* 
*AJAX调用从这个函数开始
*/
函数makeRequest()
{ 
var c=document.getElementById(“userid”).value;
var xmlHttpRequest=getXMLHttpRequest();
xmlHttpRequest.onreadystatechange=getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open(“POST”、“./userid”,true);
setRequestHeader(“内容类型”,“应用程序/x-www-form-urlencoded”);
xmlHttpRequest.send(“requestType=ajax&userid=“+c”);
} 
/* 
*返回一个函数,该函数在XMLHttpRequest中等待状态更改
*/
函数getReadyStateHandler(xmlHttpRequest){
//返回一个匿名函数
//它侦听XMLHttpRequest实例
返回函数(){
如果(xmlHttpRequest.readyState==4){
如果(xmlHttpRequest.status==200){
document.getElementById(“print”).innerHTML=xmlHttpRequest.responseText;
}否则{
警报(“HTTP错误”+xmlHttpRequest.status+”:“+xmlHttpRequest.statusText”);
} 
} 
}; 
}
用户ID
密码

请帮我解决这个问题。我需要用户id验证。如果用户ID正确,则应显示名称,否则显示错误消息。

创建一个具有数据库连接的jsp页面,该页面将被请求进行输出

在ajax请求中发送用户id,在jsp页面中获取用户id并从数据库中进行检查…如果可用,则将true发送到ajax,否则为false

或者在ajax响应中,从jsp页面获取消息结果…设置条件以处理此…。

验证用户:

  • 使用与数据库交互并返回
    boolean
    type的方法创建服务/dao类
  • 创建一个
    Servlet
    并实现
    doPost()
    并使用创建的服务/dao类
  • 最后,如果用户找到,则返回
    true
    ,否则返回
    false
  • 在javascript中,根据服务器的响应显示消息或错误
例如:

创建如下所示的
UserService
类:

public class UserService {

        public Connection getConnection() throws SQLException {
            try {
                Class.forName("com.mysql.jdbc.Driver");//register database driver
            } catch (ClassNotFoundException e) {        
                e.printStackTrace();
            }
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "****", "*****");        
        }

        /**
         * Checks a User id is exists in database using given user id<br/>
         * <b>Note:</b> this method closes Connection and PreparedStatement you have passed as parameter
         * @param pStatement A PreparedStatement instance with query to fetch result
         * @return a true if user id found in database, else false returned.         
         */
        public boolean isUserExists(final String userId) {      
            if(userId==null || userId.isEmpty())
                return false;

            //declare required fields
            Connection connection = null;
            ResultSet rSet = null;
            PreparedStatement pstmt = null;
            boolean isExists = false; //set userId exists false initially

            try{
                connection = getConnection(); //get a connection to intract with database.
                //create a PrepareStatement instance to fetch user id from database
                pstmt = connection.prepareStatement("SELECT login FROM users WHERE login=?"); 
                pstmt.setString(1, userId); // set user id which you want to retrieve from DB.
                rSet = pstmt.executeQuery(); //execute the query

                if(rSet.next()){ //check if you got any
                    System.out.printf("User id %s found",rSet.getString(1));
                    isExists = true; //user id exists, set true
                }                   
            }catch(SQLException e){
                e.printStackTrace();
            }finally{
                //close all like: Connection, ResultSet and PreparedStatement etc
                try { if (rSet != null) rSet.close(); } catch (Exception e) {};
                try { if (pstmt != null) pstmt.close(); } catch (Exception e) {};
                try { if (connection != null) connection.close(); } catch (Exception e) {};
            }

            return isExists;
        }
}
@WebServlet("/validateUserIdByAjax")
public class ValidateUserIdByAjax extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private UserService userService = new UserService();        

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost() invoked..");
        // Set response content type
        response.setContentType("text/html");       
        // Set encoding
        response.setCharacterEncoding("UTF-8");

        //get user entered id
        String userId = request.getParameter("userid");
        //return userid status 
        response.getWriter().print(userService.isUserExists(userId));                   
    }

}
然后,检查服务器的响应并用javascript显示消息,如:

 function getReadyStateHandler(xmlHttpRequest) { 

   // an anonymous function returned 
   // it listens to the XMLHttpRequest instance 
   return function() { 
    if (xmlHttpRequest.readyState == 4) { 
     if (xmlHttpRequest.status == 200) { 
         var $print = document.getElementById("print");
         var res = xmlHttpRequest.responseText;
         console.log('user status: '+res);
         if(res=="true"){
             $print.innerHTML = '<span style="color:red;">user id exists!</span>';
         }else{
             $print.innerHTML = '<span style="color:green;">user id available!</span>';
          } 
     } else { 
     alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText); 
     } 
    } 
  }; 
 }
函数getReadyStateHandler(xmlHttpRequest){ //返回一个匿名函数 //它侦听XMLHttpRequest实例 返回函数(){ 如果(xmlHttpRequest.readyState==4){ 如果(xmlHttpRequest.status==200){ var$print=document.getElementById(“print”); var res=xmlHttpRequest.responseText; console.log('用户状态:'+res); 如果(res==“true”){ $print.innerHTML='user id exists!'; }否则{ $print.innerHTML='user id available!'; } }否则{ 警报(“HTTP错误”+xmlHttpRequest.status+”:“+xmlHttpRequest.statusText”); } } }; } 就这样


注意:

  • 您的AJAX帖子url应该与您的Servlet
    url模式匹配,在我的例子中,validateUserIdByAjax是Servlet
    url模式,因此AJAX url看起来像:

    xmlHttpRequest.open(“POST”,“validateUserIdByAjax”,true)

  • 数据库驱动程序类应该在类路径中可用,在我的例子中,我使用了mySql,所以被添加到类路径中

在您的问题中,id
print
没有任何元素,因此请在使用上述示例时添加以查看消息,
比如:

检查下面我的答案。