简体   繁体   English

用户验证电子邮件和密码(Java web、servlets)

[英]user verification email and password (Java web,servlets)

I've created a simple login web where the user enters the email and password and checks if the user and password are correct then he gets redirected to a welcome.jsp page , where it says login success , I'm checking 3 emails and passwords and creating session for each one , the problem I'm facing is that if the user enters the email or password wrong after 3 attempts he will be blocked for a certain amount of time and after the time expires he can try again , I can't think of a way of doing this , is there a way in which this could be done ?我创建了一个简单的登录网站,用户在其中输入电子邮件和密码并检查用户和密码是否正确,然后他被重定向到一个welcome.jsp 页面,上面显示登录成功,我正在检查 3 个电子邮件和密码并为每个人创建会话,我面临的问题是,如果用户在 3 次尝试后输入错误的电子邮件或密码,他将被阻止一段时间,时间到期后他可以再试一次,我可以'没有想到这样做的方法,有没有办法做到这一点?

import java.io.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

//@WebServlet(name = "loginController", value = "/login")
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws 
IOException {
    String email = request.getParameter("email");
    String password = request.getParameter("password");
    String er = "Invalid user info";
    int attempts = 3;
    PrintWriter printWriter = response.getWriter();
    LoginBean loginBean = new LoginBean();

    loginBean.setEmail(email);
    loginBean.setPassword(password);

    try
    {
        if(email.equals("Mhamdoon4@gmail.com") && password.equals("pass001"))
        {
            System.out.println("Admin's Home");

            HttpSession session = request.getSession(); //Creating a session
            session.setAttribute("Mohammed", email); //setting session attribute
            request.setAttribute("email", email);

            request.getRequestDispatcher("welcome.jsp").forward(request, response);
        }
        else{
            attempts--;
            printWriter.println(attempts + " left");

        }
        if(email.equals("Mhamdoon6@gmail.com") && password.equals("pass0011"))
        {
            System.out.println("Editor's Home");

            HttpSession session = request.getSession();
            session.setAttribute("Ali", email);
            request.setAttribute("email", email);

            request.getRequestDispatcher("welcome.jsp").forward(request, response);
        }
        else{
            attempts--;
            printWriter.println(attempts + " left");
        }
        if(email.equals("Mhamdoon12@gmail.com") && password.equals("pass00901"))
        {
            System.out.println("User's Home");

            HttpSession session = request.getSession();
            session.setAttribute("Adam", email);
            request.setAttribute("email", email);

            request.getRequestDispatcher("welcome.jsp").forward(request, response);
        }
        else{
            attempts--;
            printWriter.println(attempts + " left");
        }
//            if()
//            {
//                System.out.println("Error message = Invalid info");
//                request.setAttribute("errMessage", er);
//
//                request.getRequestDispatcher("fail.jsp").forward(request, response);
//            }
    }
    catch (IOException e1)
    {
        e1.printStackTrace();
    }
    catch (Exception e2)
    {
        e2.printStackTrace();
    }
    }
public void destroy() {
}
}

The easiest way, as your example is simple (string literals checking), is keeping the attempts in the session.最简单的方法,因为你的例子很简单(字符串文字检查),是保持会话中的尝试。 This way the attempts are tied up to the session (in other words, to the browser's cookies).通过这种方式,尝试与会话相关联(换句话说,与浏览器的 cookie 相关联)。

To set the values in the session:要在会话中设置值:

request.getSession().setAttribute("loginAttempts", 3);
request.getSession().setAttribute("lastLoginAttempt", LocalDateTime.now());

To read them:阅读它们:

Integer attempts = (Integer) request.getSession().getAttribute("loginAttempts");
LocalDateTime lastLoginAttempt = (LocalDateTime) request.getSession().getAttribute("lastLoginAttempt");

Now you just have to play with the values, recalculate, and reset them after a successful login.现在,您只需在成功登录后处理这些值、重新计算并重置它们。 The variables will be kept as long as the browser session is kept.只要浏览器会话被保留,变量就会被保留。

TL;DR; TL; 博士;

I see that everyone who ends up here may need a bit of a briefing about requests and sessions.我看到最后来到这里的每个人都可能需要一些关于请求和会议的简报。

You have to understand that the piece of code that goes inside de doGet or doPost is executed every time you enter the url in the browser (The int attempts = 3; from your original post is executed every time, so it will always be 3).您必须了解每次在浏览器中输入 url 时都会执行 de doGetdoPost内部的代码段( int attempts = 3;每次都执行来自您的原始帖子,因此它始终为 3) .

The server collects all the data that comes from the client's browser request and builds a brand new HttpServletRequest object that contains all the data (url, request params, cookies, ip, port, etc.) every time.服务器收集来自客户端浏览器请求的所有数据,并构建一个全新的HttpServletRequest对象,该对象包含每次的所有数据(url、请求参数、cookie、ip、端口等)。 Press f5?按f5? everything gets executed again with a brand new HttpServletRequest .一切都使用全新的HttpServletRequest再次执行。

The way the servers use to keep a conversational state between the server and the client (browser) is through the Session.服务器用来在服务器和客户端(浏览器)之间保持对话状态的方式是通过会话。 The Session is the only thing that is kept between requests.会话是请求之间唯一保留的内容。 You can save variables in the Session for later (like the attempts and the lastLoginAttempt ), and rely on the Session to see if a user is successfully logged in.您可以在 Session 中保存变量以备后用(例如attemptslastLoginAttempt ),并依靠 Session 来查看用户是否成功登录。

And how do the server keeps the session between requests if everything gets recreated in each request?如果在每个请求中都重新创建了所有内容,服务器如何保持请求之间的会话? through the session cookie.通过会话cookie。 The server users a normal cookie to which it gives a special value (In the Servlet specification this cookie is JSESSIONID ).服务器使用一个普通的 cookie,它赋予一个特殊的值(在 Servlet 规范中,这个 cookie 是JSESSIONID )。 When a request come without that cookie the server creates one giving it the value of a unique identifier.当一个请求没有那个 cookie 时,服务器会创建一个给它一个唯一标识符的值。 Next requests from the same browser will have that cookie, and the server will use the cookie to attach the session to every HttpServletRequest generated from requests from that browser.来自同一浏览器的下一个请求将具有该 cookie,并且服务器将使用该 cookie 将会话附加到从该浏览器的请求生成的每个HttpServletRequest So in the brand new HttpServletRequest that is created in every request, the server injects into it the same HttpSession that was being used by the same JSESSIONID .因此,在每个请求中创建的全新HttpServletRequest中,服务器将同一JSESSIONID使用的相同HttpSession注入其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM