-1
我一直在面對這個問題,我知道這是一個經常被問到的問題,但問題還沒有被我的研究糾正。Servlet:登錄嘗試失敗
我面臨的問題是我創建了邏輯,如果相同的用戶名將嘗試登錄2次,它應該減少嘗試次數。但是,它總是停留在沒有嘗試2.
我基本上做了這個:我試圖使用HttpSession來計數在頁面上的訪問次數,但失敗。因爲我覺得,每當我將其重定向到我的登錄頁面。它只會重新啓動會話。
我的初步計劃是,在我的JDBC代碼中,如果用戶嘗試登錄超過3次,它將阻止user_acc == 1
。但是看到我面臨的主要問題,我決定使用基本邏輯,只需從輸入字段輸入用戶名,而無需連接到數據庫。在我糾正這個問題之後,我會修改它以將它連接到我的數據庫。
任何幫助將真正被讚賞。
String name = request.getParameter("username");
String pass = request.getParameter("password");
PrintWriter pw = response.getWriter();
int login_attempt = 3;
HttpSession session=request.getSession();
session.setAttribute("name",name);
String sessionName = (String) session.getAttribute("name");
if(name.equals("scott")){
if(pass.equals("abc"))
{
pw.println(("Success"));
pw.println(sessionName);
}
else {
login_attempt = login_attempt - 1;
if(login_attempt < 3 && sessionName.equals(name)){
pw.println(" You have this try " + login_attempt + " : " + sessionName);
} else if(login_attempt == 0 && sessionName.equals(name)){
pw.println("Please contact admin for as your account is blocked");
}
}
}
解決 爲他人謀取利益,我已經解決了這個問題
int loginAttempt;
if (session.getAttribute("loginCount") == null) {
// This will first set login count to zero
session.setAttribute("loginCount", 0);
loginAttempt = 0;
} else {
loginAttempt = (Integer) session.getAttribute("loginCount");
// System.out.println("How many attempt " + loginAttempt);
}
if (loginAttempt == 3) {
session.setMaxInactiveInterval(5);
System.out.println(("game over"));
pw.println("No more attempt please call admin\n\n");
pw.println("<br/> \n\n\n\n\n\n left for interval");
} else {
System.out.println("How many attempt " + loginAttempt);
// loginAttempt = loginAttempt + 1;
loginAttempt++;
int allowLogin = 3 - loginAttempt;
session.setAttribute("message", "loginAttempt= " + loginAttempt
+ ". Invalid username or password. You have " + allowLogin + " attempts remaining.");
System.out.println(session.getAttribute("message"));
response.sendRedirect("login.jsp");
}
if (isTrue != false) {
pw.println("Username does not exist in database");
}
session.setAttribute("loginCount", loginAttempt);
pw.println("Invalid users");
這代碼不完整。我想是在某個班級。變量login_attempt是本地的,每次拍攝都會被還原 –
我不完全明白它是如何比較用戶名以將其存儲爲會話,以及何時將其重定向到具有不正確密碼的登錄頁面。它會根據登錄失敗識別用戶名並相應地減少嘗試次數。任何想法? –
如果你解決了你自己的問題,那麼你應該把它作爲**答案**,不要將它編輯成你的問題。請從您的問題中刪除解決方案,並將其作爲答案發布。 –