1

这工作正常。现在我想在用户登录后创建一个会话,并在尝试登录失败的次数为 3 后重定向到安全问题。我该怎么做?

如何创建用户登录和注销会话?以及如何计算登录尝试次数?

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);
    }

}
4

1 回答 1

1

首先,您需要一个会话变量来存储登录尝试。所以你的 doGet() 的第一行必须是这样的:

// 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);
}

然后在您验证用户凭据后,您应该查看登录尝试计数器是否等于一个数字,并将请求适当地转发到您想要的视图。

于 2013-06-13T13:06:57.177 回答