new*_*per 7 java forms cookies session servlets
我正在尝试使用servlet创建注册页面.我创建了一个基本的HTML页面,其中包含一个输入用户名和密码的表单.现在我需要做的是使用cookie/sessions存储提交给表单的信息.然后,在登录页面上,用户必须能够使用之前提供的信息登录.所以基本上我需要知道如何存储用户名和密码.
因此,如果我使用用户名注册:admin和密码123,然后注册用户名:user和密码:12345,我应该无法使用admin和12345或用户和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>
Run Code Online (Sandbox Code Playgroud)
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 );
Run Code Online (Sandbox Code Playgroud)
Cookies存储在客户端,并随每个请求发送到服务器。在cookie中添加密码不是一个好习惯,因为它们很容易被截获,并且在许多情况下,即使他们离开站点后,它们也仍然会停留在用户浏览器中。
您应该依赖会话,Java EE允许您与用户创建会话,在该会话中,用户将存储会话ID,然后该会话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");
Run Code Online (Sandbox Code Playgroud)
当然,现在如果您用这种方法清除服务器缓存,则用户名和密码将被清除。服务器缓存中的非加密密码当然也有安全隐患。
编辑:
如果两个人要使用同一台计算机,则不能,以上代码将无法正常工作。这是因为用户凭据仅存储在会话中,在会话被销毁或会话中的数据被覆盖后,没有任何东西可以保留。假设会话是一个直接绑定到每个用户的对象。因此,现在我在StackOverflow上,在他们的代码中某个地方有一个专门用于我和我的浏览器的特殊对象(会话!),在该会话对象中还有其他一些内容表明当前登录的用户是我。我挑战您考虑如何在会话外部存储用户凭据,而在会话内部存储当前登录的用户。
要了解有关会话及其工作方式的更多信息,这里有一个很好的答案:什么是会话?它们如何工作?。