有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Cookie/sessions Java Servlets存储用户名、密码和密码的表单

我正在尝试使用servlet创建一个注册页面。我创建了一个基本的HTML页面,其中有一个输入用户名和密码的表单。现在我需要做的是使用cookies/sessions存储提交到表单的信息。然后在登录页面上,用户必须能够使用之前提供的信息登录所以基本上我需要知道如何存储用户名和密码

所以,如果我用用户名:admin和密码123注册,然后用用户名:user和密码:12345注册,我应该不能用admin和12345或user和123登录。谢谢

HTML表单

   <html>
    <head>
        <title>Registration</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body bgcolor="lightblue">

    <center>
        <h1></h1>
        <br>

        <hr>
        <br><br>
        <form action="/Registration" method="get">
            <h3> Please register to start </h3>
Username: <input type="text" name="userName">
<br>
Password: <input type="password" name="password">
<br>
<br>
<input type="submit" value="Register">
<br><br>
</form>
    </center>
    </body>
</html>

JAVA SERVLET

protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

         // Create cookies for first and last names.      
      Cookie userName = new Cookie("userName",
                      request.getParameter("userName"));
      Cookie password = new Cookie("password",
                      request.getParameter("password"));

       // Set expiry date after 24 Hrs for both the cookies.
      userName.setMaxAge(60*60*24); 
      password.setMaxAge(60*60*24); 

      // Add both the cookies in the response header.
      response.addCookie( userName );
      response.addCookie( password );

共 (1) 个答案

  1. # 1 楼答案

    Cookie存储在客户端,并随每个请求一起发送到服务器。在cookie中添加密码不是一个好的做法,因为它们很容易被拦截,而且在很多情况下,即使用户离开网站后,密码也会留在浏览器中

    您应该依赖一个会话,JavaEE允许您与用户创建一个会话,在这里它将存储一个会话id,然后与每个请求一起发送。您可以将有关该用户的信息存储在服务器上

    在这里使用代码可以创建会话

    // get the session, add argument `true` to create a session if one is not yet created.
    HttpSession session = request.getSession(true);
    
    session.setAttribute("userName", request.getParameter("userName"));
    session.setAttribute("password", request.getParameter("password"));
    
    // to get the username and password
    String userName = session.getAttribute("userName");
    String password = session.getAttribute("password");
    

    当然,如果在清除服务器缓存时这样做,用户名和密码将被删除。此外,服务器缓存中未加密的密码肯定存在安全问题


    编辑:

    如果两个人使用同一台计算机,那么不,上面的代码将无法正常工作。这是因为用户凭据仅存储在会话中,在会话被破坏或会话中的数据被覆盖后,不会有任何持久性。假设会话是一个直接绑定到每个用户的对象。所以现在我在StackOverflow上,他们的代码中有一个特殊的对象,只适合我和我的浏览器(会话!),在session对象中,还有一个表示当前登录用户是我的东西。我要求您考虑如何在会话外部存储用户凭据,而不是在会话内部存储当前登录的用户

    要了解有关会话及其工作方式的更多信息,这里有一个很好的答案:What are sessions? How do they work?