JavaWeb Speed Pass Session

Table of contents

1. Introduction of Session

        1.What is Session?

        2.Basic principles of Session: 

        3.What does a Session look like?

2. The underlying mechanism of Session

        1. Methods related to Session interface: 

            1° req.getSession() :

            2° httpSession.setAttribute(String name, Object val); 

            3° Object obj = httpSession.getAttribute(String name);

            4° httpSession.removeAttribute(String name) : 

            5° isNew() : 

            6° getId() : 

        2. Illustration of the underlying mechanism of the getSession() method: 

        3.JSESSIONID packet capture example: 

            1° Create Session

            2° Read Session

3. Session life cycle

        1.Basic features: 

        2.Details: 

        3. Application examples: 


1. Introduction of Session

        1.What is Session?

        (1) Session is a server-side technology, that is, Session data is stored on the server side ; the server creates an exclusive session objectfor each user's browser at runtime

        (2) Since the session object is exclusive to each user's browser, each user can read/add data from their respective sessions when accessing different pages of the server, and realize their own manipulation of their own related data.

        (3) Session can be used to save shopping cart information in online shopping malls, website login user information, etc. It can also prevent users from illegally logging into a certain page.

        2.Basic principles of Session: 

                The schematic diagram is as follows: 

                  When a user opens a browser, visits a website, and operates a session , the server will allocate a unique session object to the browser in the server-side memory , and the session object is exclusively occupied by the browser.
                2° The session object can also be regarded as a container/collection. The default existence time of the session object is 30 minutes (server side) . (Can be changed through the conf/web.xml configuration file in the tomcat installation directory)

        3.What does a Session look like?

        Session is a container similar to HashMap, which also stores (key-value pairs). Each row is an attribute of the session. Each attribute contains two parts, the former is the name of the attribute (String type), and the latter is the value of the attribute (Object type) .

        As shown below: 


2. The underlying mechanism of Session

        1. Methods related to Session interface: 

            1° req.getSession() :

                HttpSession httpSession = req.getSession() ; This method is used to return the Session object, which is actually an implementation class object that implements the Session interface. The first call to this method is to create a Session, and subsequent calls are to obtain the created Session object.

            2° httpSession.setAttribute(String name, Object val); 

This method is used to add properties                 to the Session object .

            3° Object obj = httpSession.getAttribute(String name);

                Object obj = httpSession.getAttribute(String name); Polymorphic downward transformation can also be considered. This method is used to get a certain attribute from the Session object .

            4° httpSession.removeAttribute(String name) : 

                This method is used to delete an attribute from the Session object.

            5° isNew() : 

                This method is used to determine whether it is a newly created Session object.

            6° getId() : 

                Each Session object has a unique Id value, namely JSESSIONID; you can get the session Id value of the Session through getId().

        2. Illustration of the underlying mechanism of the getSession() method: 

                The schematic diagram is as follows: (three lines in total)

                Contact the implementation mechanism of the container in the underlying mechanism of handwritten Tomcat .

        3.JSESSIONID packet capture example: 

            1° Create Session

                The CreateSessionServlet class code is as follows: 

package bottom;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : Cyan_RA9
 * @version : 21.0
 */
@WebServlet(urlPatterns={"/createSession"})
public class CreateSessionServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取session对象(也可能是创建)
        HttpSession httpSession = req.getSession();
        System.out.println("httpSession = " + httpSession);

        //获取Session对象的Id
        String sessionId = httpSession.getId();
        System.out.println("sessionId = " + sessionId);

        //向Session容器中存放数据
        httpSession.setAttribute("fruit", "Grape");

        //回显
        resp.setContentType("text/html; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>Getting the session!</h1>");
        writer.flush();
        writer.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

                The running effect is as follows (GIF):

            2° Read Session

                The ReadSessionServlet class code is as follows: 

package bottom;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : Cyan_RA9
 * @version : 21.0
 */
@WebServlet(urlPatterns={"/readSession"})
public class ReadSessionServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession httpSession = req.getSession();
        System.out.println("Read's sessionId = " + httpSession.getId());

        //传入name来获取Session属性
        Object fruit = httpSession.getAttribute("fruit");
        if (fruit != null) {
            System.out.println("Session属性fruit = " + (String) fruit);
        } else {
            System.out.println("找不到\"name = fruit\"的session属性!");
        }

        resp.setContentType("text/html; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>Reading the session!</h1>");
        writer.flush();
        writer.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

                The running effect is as follows GIF: (Note, create attributes first, then get attributes! )


3. Session life cycle

        1.Basic features: 

                public void setMaxInactiveInterval(int interval): Set the session timeout (in seconds) . If the specified time is exceeded, the session will be destroyed.
                     When the interval value is a positive number, set the Session timeout duration.
                     When the interval value is a negative number, it means that the Session will never time out.
                 public int getMaxInactiveInterval():  Get the timeout time of the Session
                 Public void invalidate(): Invalidate the current Session immediately
                 If setMaxInactiveInterval() is not called Specify the lifetime of the Session. Tomcat will use the default Session duration as the standard. The default Session timeout is 30 minutes , which can be set in tomcat's web.xml.

        2.Details: 

        The life cycle of Session refers to the maximum interval between two requests by the client / browser , not the cumulative duration . That is, when the client accesses its own session, the session life cycle will be recalculated from 0 ; that is, it refers to the time interval between two requests for the same session.
        Tomcat will use a thread at the bottom to poll the session status . If the idle time of a session exceeds the set maximum value, the session will be destroyed.

        3. Application examples: 

                The CreateSession_EX class code is as follows: 

package lifetime;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns={"/createEX"})
public class CreateSession_EX extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取Session对象
        HttpSession httpSession = req.getSession();
        System.out.println("CreateEX's sessionId = " + httpSession.getId());

        //设置Session对象的生命周期 = 30s
        httpSession.setMaxInactiveInterval(20);

        //设置Session对象的属性
        httpSession.setAttribute("animal", "Cat");

        //回显给浏览器
        resp.setContentType("text/html; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>创建Session!生命周期20s。</h1>");
        writer.flush();
        writer.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

                ReadSession_EX class code is as follows: 

package lifetime;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns={"/readEX"})
public class ReadSession_EX extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取Session对象
        HttpSession session = req.getSession();
        System.out.println("ReadEX's sessionId = " + session.getId());

        int maxInactiveInterval = session.getMaxInactiveInterval();
        System.out.println("当前Session生命周期 = " + maxInactiveInterval);

        //获取Session中的属性
        Object animal = session.getAttribute("animal");
        if (animal != null) {
            System.out.println("animal = " + (String) animal);
        } else {
            System.out.println("原先的Session已经被销毁!");
        }

        //回显
        resp.setContentType("text/html; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>读取Session!</h1>");
        writer.flush();
        writer.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

                Running effect: (GIF below)

        System.out.println("END----------------------------------------------------------------------------------------------------------------------");

Guess you like

Origin blog.csdn.net/TYRA9/article/details/132170804