通過Ajax從Servlet獲取資料完成登入例項
阿新 • • 發佈:2019-02-20
Ajax的好處就是可以在頁面不進行重新整理的情況下,完成當前頁面某些收據的更新,速度快且使用者體驗好。
剛開始學習,就著幾行程式碼也要搞很長時間才能明白。
login.jsp--登入介面
js-bbs.js--js檔案登入驗證,其中包括正則判斷和資料庫的驗證判斷<span style="white-space:pre"> </span><form action="" method="post" onsubmit="return logincheck();"> <span style="white-space:pre"> </span><div class="login_row login_row_text"> <span style="white-space:pre"> </span><label id="login_lab_user" class="login_lab"></label> <span style="white-space:pre"> </span><input id="loginname" class="itext" type="text" name="username" tabindex="1" autocomplete="off" <span style="white-space:pre"> </span>placeholder="郵箱/使用者名稱/已驗證手機"> <span style="white-space:pre"> </span></div> <span style="white-space:pre"> </span><div class="login_row login_row_text"> <span style="white-space:pre"> </span><label id="login_lab_pwd" class="login_lab"></label> <span style="white-space:pre"> </span><input id="signpwd" class="itext" type="password" name="password" tabindex="2" autocomplete="off" <span style="white-space:pre"> </span>placeholder="密碼"> </div> <span style="white-space:pre"> </span><div class="login_row"> <span style="white-space:pre"> </span><input id="loginbut" type="submit" name="login_sub" value="登 錄" tabindex="4"> <span style="white-space:pre"> </span></div><div id="meserror"><ul id="meserrorul"></ul></div> <span style="white-space:pre"> </span></form>
因為不想get傳送所以就從網上學習了一種建立虛擬表單的方式來post想要傳送到servlet的內容,當post傳到servlet之後,通過“out.print();”回傳想要接受的值,這時遇到了一個問題,我想要從在servlet中通過資料庫中驗證當沒有查詢到的時候就返回代表錯誤資訊的字串,查詢到了,就直接通過servlet直接跳轉到主頁,跳轉主頁使用/*login.jsp 登入驗證*/ function logincheck() { var uname = document.getElementById("loginname"); var upwd = document.getElementById("signpwd"); console.log(uname.value," ",upwd.value); if(uname.value == "" || uname.value == null) { var cul = document.getElementById("meserrorul"); cul.innerHTML = "<li>賬號不能為空</li>"; document.getElementById("meserror").style.display = ""; return false; }else if(upwd.value == "" || upwd.value == null) { var cul = document.getElementById("meserrorul"); cul.innerHTML = "<li>密碼不能為空</li>"; document.getElementById("meserror").style.display = ""; return false; }else if(upwd.value == "" || upwd.value == null) { var cul = document.getElementById("meserrorul"); cul.innerHTML = "<li>密碼不能為空</li>"; document.getElementById("meserror").style.display = ""; return false; }else { //通過AJAX從資料庫中驗證 var xhr; if (window.ActiveXObject) { //測試ActiveX是否存在 try { xhr = new ActiveXObject("Microsoft.XMLHTTP");//低版本IE } catch (e) { xhr = new ActiveXObiect("Msxml2.XMLHTTP");//高版本IE } } else if (window.XMLHttpRequest) { //測試XHR是否已經被定義 xhr = new XMLHttpRequest(); } else { //如果不支援AJAX則丟擲錯誤 throw new Error("Ajax is not supported by this browser"); } //就緒狀態處理器 xhr.onreadystatechange = function() { if(this.readyState == 4) { //忽略除DONE狀態之外的所有狀態 if (this.status >= 200 && this.status <300) { //成功 var data = xhr.responseText; console.log(data); if(data=="fail"){ console.log("Active data"); var cul = document.getElementById("meserrorul"); cul.innerHTML = "<li>賬號/密碼錯誤</li>"; document.getElementById("meserror").style.display = ""; }else { var url = "LoginSuccess";<span style="white-space:pre"> </span>//servlet路徑 // location.href=url;//get傳送 post(url, {userId:data}); } } else { //出錯 location.href="error.jsp"; } } }; xhr.open("GET", "Login?username=" + uname.value + "&password=" + upwd.value,true); xhr.send(null); return false; } }; //post虛擬表單 function post(URL, PARAMS) { var temp = document.createElement("form"); temp.action = URL; temp.method = "post"; temp.style.display = "none"; for (var x in PARAMS) { var opt = document.createElement("textarea"); opt.name = x; opt.value = PARAMS[x]; // alert(opt.name) temp.appendChild(opt); } document.body.appendChild(temp); temp.submit(); return temp; }
request.getRequestDispatcher("home.jsp").forward(request, response);
可是這樣的話Ajax就把整個jsp檔案的內容都傳回js檔案中了,無法跳轉到主頁,不知道什麼好的辦法,所以自己就想了一種讓驗證資訊返回到js檔案中,js檔案再把引數傳到另一個servlet的方法來進行頁面跳轉
Login.java--登入驗證Servlet,返回驗證結果
<span style="white-space:pre"> </span>String username = request.getParameter("username").trim();
String userpwd = request.getParameter("password").trim();
PrintWriter out = response.getWriter();
try {
Connection conn = MySQLDbHelper.getConnection();
Statement stmt = MySQLDbHelper.creStatement(conn);
String sql = "SELECT safeuserid FROM SafeUser WHERE safeusername='"+username+"' AND safepassword= '"+userpwd+"'";
ResultSet rs = MySQLDbHelper.executeQuery(stmt, sql);
if(rs.next()) {
String userid = rs.getString("safeuserid");
MySQLDbHelper.close(rs);
MySQLDbHelper.close(stmt);
MySQLDbHelper.close(conn);
out.print(userid);
} else {
out.print("fail");
}
} catch (Exception e) {
// TODO: handle exception
response.sendRedirect("error.jsp");
}
LoginSuccess.java--跳轉servlet,通過驗證後的傳值和跳轉
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String userId = request.getParameter("userId");
HttpSession session = request.getSession(true);
String sql = "SELECT safeusername FROM SafeUser WHERE safeuserid='"+userId+"'";
try {
Connection conn = MySQLDbHelper.getConnection();
Statement stmt = MySQLDbHelper.creStatement(conn);
ResultSet rs = MySQLDbHelper.executeQuery(stmt, sql);
if (rs.next()) {
String sUserName = rs.getString("safeusername");
session.setAttribute("userName", sUserName);
session.setAttribute("userId", userId);
rs.close();
stmt.close();
conn.close();
request.getRequestDispatcher("home.jsp").forward(request, response);
}
} catch (Exception e) {
// TODO: handle exception
}
}
到了這裡我的登入就完成了