📅  最后修改于: 2023-12-03 14:47:24.865000             🧑  作者: Mango
本示例演示了如何使用Servlet的HttpSession来实现用户的登录和注销功能。
要实现登录功能,需要进行以下步骤:
login.html
),包含用户名和密码的输入字段,以及一个提交按钮。LoginServlet
),用于处理登录请求。在该Servlet中,将获取用户输入的用户名和密码,并与预先存储的正确用户名和密码进行比较。home.html
),否则将用户重定向回登录页面,并显示错误消息。下面是示例代码:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="login" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
// 检查用户名和密码是否有效(此处仅作示例,实际应与数据库或其他存储进行比较)
if (username.equals("admin") && password.equals("password")) {
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("home.html");
} else {
response.sendRedirect("login.html?error=1");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome, ${session.username}!</h1>
<a href="logout">Logout</a>
</body>
</html>
要实现注销功能,需要进行以下步骤:
LogoutServlet
),用于处理注销请求。在该Servlet中,将销毁当前HttpSession,并重定向回登录页面。下面是示例代码:
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
response.sendRedirect("login.html");
}
}
以上示例演示了如何使用Servlet的HttpSession来实现用户的登录和注销功能。可以根据实际需求进行修改和扩展。