2014-10-05 74 views
5

我正在嘗試使用servlet創建註冊頁面。我創建了一個基本的HTML頁面,其中有一個輸入用戶名和密碼的表單。現在我需要做的是使用cookies /會話存儲提交給表單的信息。然後在登錄頁面上,用戶必須能夠使用他們之前提供的信息進行登錄。 所以基本上我需要知道如何存儲用戶名和密碼。使用cookie /會話存儲用戶名,密碼 - Java Servlets

因此,如果我註冊用戶名:admin和密碼123,然後註冊用戶名:user和password:12345,我不應該能夠用admin和12345或user和123登錄。 !

HTML FORM

<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); 
+0

歡迎來到Stack Overflow。本網站面向具體問題並附有具體答案。你已經給了我們一個相當高的要求和一段代碼,這是這個網站的主題。你應該閱讀一些教程,嘗試一下,如果你有一個具體的問題,你可以在這裏提問。一句警告:任何與安全有關的事情都是棘手的,做錯的後果是非常嚴重的,所以你最好使用一個能夠爲你處理它的框架。 – yshavit 2014-10-05 20:38:52

回答

4

Cookies是存儲在客戶端和被髮送到與每個請求的服務器。在cookies中添加密碼並不是一種好的做法,因爲它們很容易被攔截,並且在很多情況下甚至在用戶瀏覽器離開網站後仍然存在。

您應該依賴一個會話,Java EE允許您與用戶創建一個會話,然後它將存儲一個會話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"); 

當然,如果您在清除服務器緩存時執行此操作,用戶名和密碼將被刪除。服務器緩存中的非加密密碼當然也存在安全問題。


編輯:

如果2人使用同一臺計算機則沒有,上面的代碼將無法正常工作。這是因爲用戶憑證只存儲在會話中,會話銷燬或會話中的數據被覆蓋後沒有任何內容存在。想象一下,會話是直接綁定到每個用戶的對象。所以現在我在StackOverflow上,在代碼的某個地方有一個特殊的對象,只是我和我的瀏覽器(會話!),在會話對象中還有一些其他的說當前登錄用戶是我。我挑戰你考慮如何在會話之外存儲用戶憑證,並將當前登錄的用戶存儲在會話中。

要了解有關會議及其工作方式的更多信息,請點擊此處:What are sessions? How do they work?

+0

感謝您的回覆!如果不止一個用戶在同一個會話期間註冊,這個代碼是否工作?此外,我得到這個錯誤 找不到符號 符號:方法addAttribute(字符串,字符串) 位置:HttpSession類型的變量會話 – newbdeveloper 2014-10-06 00:06:13

+1

它的session.setAttribute(),而不是addAttribute(); – 2016-04-22 09:25:57