使用cookie /会话存储用户名,密码 - Java Servlets
我正在尝试使用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);
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人使用同一台计算机则没有,上面的代码将无法正常工作。这是因为用户凭证只存储在会话中,会话销毁或会话中的数据被覆盖后没有任何内容存在。想象一下,会话是直接绑定到每个用户的对象。所以现在我在*上,在代码的某个地方有一个特殊的对象,只是我和我的浏览器(会话!),在会话对象中还有一些其他的说当前登录用户是我。我挑战你考虑如何在会话之外存储用户凭证,并将当前登录的用户存储在会话中。
要了解有关会议及其工作方式的更多信息,请点击此处:What are sessions? How do they work?。
感谢您的回复!如果不止一个用户在同一个会话期间注册,这个代码是否工作?此外,我得到这个错误 找不到符号 符号:方法addAttribute(字符串,字符串) 位置:HttpSession类型的变量会话 – newbdeveloper 2014-10-06 00:06:13
它的session.setAttribute(),而不是addAttribute(); – 2016-04-22 09:25:57
欢迎来到Stack Overflow。本网站面向具体问题并附有具体答案。你已经给了我们一个相当高的要求和一段代码,这是这个网站的主题。你应该阅读一些教程,尝试一下,如果你有一个具体的问题,你可以在这里提问。一句警告:任何与安全有关的事情都是棘手的,做错的后果是非常严重的,所以你最好使用一个能够为你处理它的框架。 – yshavit 2014-10-05 20:38:52