我想使用Ajax进行UserId验证,任何人都可以帮我连接数据库吗?
这是我的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>
请帮我解决这个问题。我需要用户ID验证。如果正确的用户标识,那么它应该显示名称,否则显示错误消息。
答案 0 :(得分:1)
验证用户:
boolean
类型的方法创建服务/ dao类。Servlet
并实施doPost()
并使用已创建的服务/ dao类。true
,否则返回false
。例如:
创建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;
}
}
和Servlet看起来像:
@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);
}
}
};
}
就是这样。
注意:
您的AJAX POST网址应该与您的Servlet url-patteren
匹配,在我的情况下 validateUserIdByAjax 是servlet url-pattern
所以AJAX网址将如下所示:
xmlHttpRequest.open("POST", "validateUserIdByAjax", true);
。
并且数据库驱动程序类应该在CLASSPATH中可用,在我的情况下,我使用了mySql,因此将mysql-connector-java.jar添加到CLASSPATH。
在您的问题中,没有任何ID print
的元素,所以请在使用上面的示例时添加以查看消息,
喜欢:<span id="print"></span>
答案 1 :(得分:0)
创建一个具有数据库连接的jsp页面,该页面将被请求输出.....
在你的ajax请求中发送user_id并在jsp页面中获取userid并从数据库中检查...如果可用则将true发送给ajax,否则为false .....
或者在ajax响应中从jsp页面获取消息结果... make条件来处理这个........