📜  Servlet HttpSession登录和注销示例(1)

📅  最后修改于: 2023-12-03 14:47:24.865000             🧑  作者: Mango

Servlet HttpSession登录和注销示例

本示例演示了如何使用Servlet的HttpSession来实现用户的登录和注销功能。

登录功能

要实现登录功能,需要进行以下步骤:

  1. 创建一个登录页面 (login.html),包含用户名和密码的输入字段,以及一个提交按钮。
  2. 创建一个Servlet (LoginServlet),用于处理登录请求。在该Servlet中,将获取用户输入的用户名和密码,并与预先存储的正确用户名和密码进行比较。
    • 如果用户名和密码匹配,将创建一个新的HttpSession,并将登录状态信息存储在Session中。
    • 如果用户名和密码不匹配,将返回错误信息给用户。
  3. 如果登录成功,将用户重定向到一个受保护的页面 (home.html),否则将用户重定向回登录页面,并显示错误消息。

下面是示例代码:

login.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>

LoginServlet.java

@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");
        }
    }
}

home.html

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>Welcome, ${session.username}!</h1>
    <a href="logout">Logout</a>
</body>
</html>
注销功能

要实现注销功能,需要进行以下步骤:

  1. 创建一个注销Servlet (LogoutServlet),用于处理注销请求。在该Servlet中,将销毁当前HttpSession,并重定向回登录页面。

下面是示例代码:

LogoutServlet.java

@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来实现用户的登录和注销功能。可以根据实际需求进行修改和扩展。