问题
This works fine. Now I wanna create a session after user logged in and also redirect to security questions once the number of unsuccessful attempts to login is 3. How can I do that?
How to create a user login and logout session? And how to count the number of login attempts?
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mutualfund", "root", "");
Statement stmt = con.createStatement();
String uname = request.getParameter("username");
String pass = request.getParameter("password");
String query = "SELECT * FROM `login_table` WHERE `username`=\""+uname +"\" and `password`=\""+pass+"\"";
ResultSet result = stmt.executeQuery(query);
if(result.next())
{
System.out.println("entered into if loop");
if (result.getString(1).equals(uname)
&& result.getString(2).equals(pass)) {
System.out.println("Uname and pass are correct");
if (result.getBoolean(7) == true) {
System.out.println("redirecting to admin profile");
response.sendRedirect("displayFunds.jsp");
}
else if ((result.getBoolean(7) == false)
&& (result.getInt(3)==0)) {
System.out.println("first time login for customer, redirecting to change pass");
response.sendRedirect("changePassword.jsp?name="
+ uname + "&&pass=" + pass);
}
else if ((result.getBoolean(7) == false)
&& (result.getInt(3)==1)) {
System.out.println("active customer login");
response.sendRedirect("custProfile.jsp");
}
}
else {
response.sendRedirect("loginFailed.jsp");
}
}
} catch (Exception ex) {
Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
}
}
回答1:
First of all you need a session variable to store in login attempts. So the first line of your doGet() must be something like this:
// Do not create session if it doesn't exist
HttpSession session = request.getSession(false);
int loginAttempts=0;
try{
loginAttempts = Integer.parseInt(session.getAttribute("LOGIN_ATTEMPTS").toString());
loginAttempts++; //if code comes here then the user has already made a login attempt and therefore icrease the counter
}catch(Exception ex){
//if error then that means that the user has never made a login attempt because the attribute was not found
session.setAttribute("LOGIN_ATTEMPTS",1);
}
Then after you validate the user credentials you should see if the login attempts counter is equals to a number and forward the request appropriately to the view you want.
来源:https://stackoverflow.com/questions/17087000/creating-sessions-for-my-login-page-and-counting-number-of-unsuccessful-login