Data sharing between different requests of the same user. When a user accesses the server for the first time, the server will create a session object for the user and store it in the server, and store the JSESSIONID of the session object in the browser using Cookie technology. To ensure that other requests of users can obtain the same session object, and to ensure that different requests can obtain shared data, the scope is a conversation, which is more important than cookies, it is stored in the server, relatively safe.

HttpSession hs = req.getSession() // Get the session object

Hs.setattribute (String Name, Object Value) // Stores data

Hs. getAttribute(String name) // Gets data. The return type is Object

Hs.getid () // Obtain the JSESSIONID

The hs. SetMaxInactiveinterval (seconds) / / set the valid time of the session

Hs.invalidate () // Sets a forcible session invalidation

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

@WebServlet("/a")
public class SessionDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.setAttribute("username"."root");
        String id = session.getId();
        Object username = session.getAttribute("username");
        System.out.println(id + "-- -- -- -- -- -" + username);
    }

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