The working principle of session, and the example of login verification using session

Session is a server-side state management mechanism commonly used in Web development. It is used to store user session information on the server side to achieve cross-page and cross-request data sharing. The working principle of Session involves the following main steps:

  • Client request: When a user accesses a website through a browser, the browser sends an HTTP request to the server.

  • Server creates Session: After the server receives the request, if the request does not carry a valid Session identifier (such as Session ID), the server will create a new Session for the user. The Session ID is usually a unique identifier that can be passed between the client and server via a cookie, or via URL parameters (not recommended).

  • Session data storage: The server will store the user's session information in server memory or persistent storage (such as a database). Session data is usually in the form of key-value pairs and is used to store the user's status, login information, shopping cart contents, etc.

  • Session ID sent to the client: The server will send the Session ID to the client in the HTTP response through Cookie or URL parameters. The client browser will save this Session ID.

  • Client request carries Session ID: In subsequent requests, the client will carry the previously obtained Session ID in the HTTP request.

  • The server retrieves Session data: When the server receives the client's request, it will retrieve the corresponding Session data based on the Session ID in the request.

  • Session data usage: The server can determine the user's login status based on the Session data, obtain previously stored user information, etc., and then process the request based on business logic.

  • Session timeout: Normally, Session has a timeout period, that is, when a user does not initiate a new request within a period of time, the server will automatically delete the user's Session data to release server resources.

It should be noted that the use of Session requires reasonable consideration, especially in a distributed environment, and the sharing and synchronization issues of Session need to be specially dealt with. For large-scale applications, you can consider using a distributed cache or database to store Session data to achieve high availability and scalability.

Java example of session judgment login

  1. User login: After the user successfully logs in, the user's login information is stored in the Session.

  2. User logout: Clear the login information in the Session when the user logs out or logs out.

  3. Pages or operations that require login permissions: On pages or operations that require login permissions, check whether login information exists in the Session. If it exists, it means that the user has logged in and can continue to access; if it does not exist, it will jump to the login page or perform other processing.

The following is a simple Java example that demonstrates how to use Session to determine whether the user is logged in:

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 假设这里有一个验证登录的逻辑,验证成功则创建 Session
        if (isValidUser(username, password)) {
    
    
            HttpSession session = request.getSession(true); // 创建或获取 Session
            session.setAttribute("username", username); // 将用户名存储到 Session
            response.sendRedirect("welcome.jsp"); // 登录成功后重定向到欢迎页面
        } else {
    
    
            response.sendRedirect("login.jsp?error=1"); // 登录失败返回登录页面并带上错误信息
        }
    }

    // 假设这里有一个验证登录的方法
    private boolean isValidUser(String username, String password) {
    
    
        // 实际验证逻辑在此处实现
        return true;
    }
}

Welcome page (welcome.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <title>Welcome Page</title>
</head>
<body>
    <c:if test="${empty sessionScope.username}">
        <h1>Please login to access this page!</h1>
        <a href="login.jsp">Login</a>
    </c:if>
    <c:if test="${not empty sessionScope.username}">
        <h1>Welcome, ${
    
    sessionScope.username}!</h1>
        <a href="logout">Logout</a>
    </c:if>
</body>
</html>

In this example, LoginServlet is used to verify user login and create Session. The welcome.jsp page checks whether the login information exists in the Session through the JSTL tag library to determine whether the user is logged in. If the user is not logged in, the login link is displayed; if the user is logged in, the welcome message and logout link are displayed.

When a user accesses a page that requires login permission, the Servlet or Controller layer code can also determine whether the user is logged in based on the Session, thereby deciding whether to continue executing the business logic.

Guess you like

Origin blog.csdn.net/wang121213145/article/details/131977473