javaWeb-7-Session mechanism

table of Contents

1. Session mechanism

2. Cookie mechanism

2.1 What is a cookie

3. Session mechanism

2.1 What is Session

2.2 Session creation and acquisition (id number, whether it is new)-project structure-API collection

2.2.1 Write a Servlet dynamic processor SessionServlet

2.2.2 Configure the access path of the Servlet dynamic processor in the web.xml file

2.2.3 Write a front-end test HTML page: session.html

2.2.4 HTTP request test: Session creation and acquisition (id number, whether it is new)

2.3 Storage and acquisition of data in the session domain

2.3.1 First: Write Servlet Processor

2.3.2 Second: Writing the front-end page-session.html

2.3.3 Third: Configure the access path of the servlet processor in the web.xml file

2.3.4 Fourth: Test and test results

2.4 Session life cycle control

2.4.1 First: Create a Servlet Processor

2.4.2 Second: Configure the access path in the web.xml file

2.4.3 Third: Write a front-end page-session.html

2.4.4 Fourth: Test and Results

2.5 The technical inside story of the browser and Session association

2.5.1 Illustration: how the browser and the session object are related at the bottom

2.5.2 Text: how the browser and the session object are related at the bottom

1. Session mechanism

(1) Session: A session contains multiple requests and multiple responses. Note: A session means that the browser sends a request to the server for the first time, and the session is established until one party is disconnected.

(2) Function: Data is shared between multiple requests in a session.

(3) Method: Cookie: Client session technology . Session: Server-side session technology .

2. Cookie mechanism

2.1 What is a cookie

(1) Cookie translates to "biscuits".

(2) Cookie is a client session technology that the server informs the client to save key-value pairs.

(3) After the client has a cookie, each request can send the cookie to the server, and the content of the cookie can be parsed in the server.

(4) The size of each cookie cannot exceed 4KB.

3. Session mechanism

2.1 What is Session

(1) Session is an interface (HttpSession).

(2) Session is a kind of session, which is a server-side session technology used to maintain the correlation between the client and the server.

(3) Each client has its own Session session.

(4) In the Session session, we often use to save some information about the user's login.

2.2 Session creation and acquisition (id number, whether it is new)-project structure-API collection

(1) How to create and obtain a Session? Their API is the same: request.getSession( );

        1) When this method is called for the first time: it is to create a Session.

        2) Not the first call, that is, when it is called later: it is to get the Session object that has been created before.

(2) So how to judge whether the method [request.getSession( );] is called for the first time: isNew( ); Used to judge whether the Session object is just created or new.

        1) true: indicates that this is the Session object just created.

        2) false: It means to get the Session object that has been created before.

(3) Each Session object has its own ID number, which is the ID value. Note: This ID value is unique. Use the method [getId( );] to get the session ID value of this Session object.

  

2.2.1 Write a Servlet dynamic processor SessionServlet

(1) Write a method to create and get session in the dynamic processor: createOrGetSession

package com.wind.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.Method;

/**
    //测试1:创建session会话对象和获取session会话对象
 */
public class SessionServlet extends HttpServlet {

    private static final long serialVersionUID = 3312652355957854184L;

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

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决POST请求中的中文乱码问题,一定要在获取请求参数之前调用才有效
        request.setCharacterEncoding("UTF-8");
        //解决响应中的中文乱码问题
        response.setContentType("text/html; charset=UTF-8");

        String action = request.getParameter("action");
        try {
            //反射方式:获取action业务鉴别字符串,获取相应的业务方法
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(new SessionServlet(), request, response);
        } catch (Exception e) {
            System.out.println("SessionServlet error..." + e);
        }
    }
    
    //测试1:创建session会话对象和获取session会话对象
    private void createOrGetSession(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.创建和获取session会话对象
        HttpSession session = request.getSession();
        //2.判断当前的session会话对象是否是新创建出来的
        boolean aNew = session.isNew();
        //3.获取当前的session会话对象的唯一标识ID值
        String sessionId = session.getId();
        response.getWriter().write("获取了session,它的ID值=" + sessionId + "<br/>");
        response.getWriter().write("这个session是否是新建的=" + aNew + "<br/>");
    }
}

 

2.2.2 Configure the access path of the Servlet dynamic processor in the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>SessionServlet</servlet-name>
        <servlet-class>com.wind.servlet.SessionServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>SessionServlet</servlet-name>
        <url-pattern>/sessionServlet</url-pattern>
    </servlet-mapping>

</web-app>

2.2.3 Write a front-end test HTML page: session.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <title>Cookie</title>
    <base href="http://localhost:8080/13_cookie_session/">
    <style type="text/css">
        ul li {
            list-style: none;
        }
    </style>
</head>
<body>
<iframe name="target" width="500" height="200" style="..."></iframe>
<div style="...">
    <ul>
        <li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号是否为新创建)</a></li>
        <li><a href="sessionServlet?action=" target="target">Session域数据的存储</a></li>
        <li><a href="sessionServlet?action=" target="target">Session域数据的获取</a></li>
        <li>Session的生存周期</li>
        <li>
            <ul>
                <li><a href="sessionServlet?action=" target="target">Session的默认超时时间和配置</a></li>
                <li><a href="sessionServlet?action=" target="target">Session的3秒超时销毁</a></li>
                <li><a href="sessionServlet?action=" target="target">Session马上销毁</a></li>
            </ul>
        </li>
        <li><a href="sessionServlet?action=" target="target">浏览器和Session绑定的原理</a></li>
    </ul>
</div>
</body>
</html>

2.2.4 HTTP request test: Session creation and acquisition (id number, whether it is new)

(1) The first time you click [Create and Obtain Session], it is true.

(2) It is false when it is not the first time to click [Session creation and acquisition]: it means that in this Session session, a Session session object that connects the server and the client has been created during the first visit. Obtain and use it directly in subsequent requests.

2.3 Storage and acquisition of data in the session domain

(1)设置值:request.getSession().setAttribute("key1", "value1");

(2) Get the value: object = session.getAttribute(name);

2.3.1 First: Write Servlet Processor

package com.wind.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.Method;

/**
    //测试2:Session域数据的存储
    //测试3:Session域数据的获取
 */
public class SessionServlet extends HttpServlet {

    private static final long serialVersionUID = 3312652355957854184L;

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

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决POST请求中的中文乱码问题,一定要在获取请求参数之前调用才有效
        request.setCharacterEncoding("UTF-8");
        //解决响应中的中文乱码问题
        response.setContentType("text/html; charset=UTF-8");

        String action = request.getParameter("action");
        try {
            //使用反射技术:获取action业务鉴别字符串,获取相应的业务方法
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(new SessionServlet(), request, response);
        } catch (Exception e) {
            System.out.println("SessionServlet error..." + e);
        }
    }

    //测试1:创建session会话对象和获取session会话对象
    private void createOrGetSession(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.创建和获取session会话对象
        HttpSession session = request.getSession();
        //2.判断当前的session会话对象是否是新创建出来的
        boolean aNew = session.isNew();
        //3.获取当前的session会话对象的唯一标识ID值
        String sessionId = session.getId();
        response.getWriter().write("获取了session,它的ID值=" + sessionId + "<br/>");
        response.getWriter().write("这个session是否是新建的=" + aNew + "<br/>");
    }

    //测试2:Session域数据的存储
    private void setAttribute(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.获取Session会话对象
        HttpSession session = request.getSession();
        //2.向Session对象中存储数据
        session.setAttribute("key1", "value1");
        response.getWriter().write("已经向Session中存储了数据<br/>" + session);
    }
    
    //测试3:Session域数据的获取
    private void getAttribute(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.想要从Session对象中获取的值的key
        String name = "key1";
        //2.使用自己编写的Session工具类获取对应的value
        Object attribute = SessionUtils.getAttribute(name, request);
        //3.输出到客户端展示
        response.getWriter().write("从Session对象中已经找到了想要的数据<br/>" + "key=" + name + "value=" + attribute);
    }
}

2.3.2 Second: Writing the front-end page-session.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <title>Cookie</title>
    <base href="http://localhost:8080/13_cookie_session/">
    <style type="text/css">
        ul li {
            list-style: none;
        }
    </style>
</head>
<body>
<iframe name="target" width="500" height="200" style="..."></iframe>
<div style="...">
    <ul>
        <li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号是否为新创建)</a></li>
        <li><a href="sessionServlet?action=setAttribute" target="target">Session域数据的存储</a></li>
        <li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a></li>
        <li>Session的生存周期</li>
        <li>
            <ul>
                <li><a href="sessionServlet?action=" target="target">Session的默认超时时间和配置</a></li>
                <li><a href="sessionServlet?action=" target="target">Session的3秒超时销毁</a></li>
                <li><a href="sessionServlet?action=" target="target">Session马上销毁</a></li>
            </ul>
        </li>
        <li><a href="sessionServlet?action=" target="target">浏览器和Session绑定的原理</a></li>
    </ul>
</div>
</body>
</html>

2.3.3 Third: Configure the access path of the servlet processor in the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>SessionServlet</servlet-name>
        <servlet-class>com.wind.servlet.SessionServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>SessionServlet</servlet-name>
        <url-pattern>/sessionServlet</url-pattern>
    </servlet-mapping>

</web-app>

2.3.4 Fourth: Test and test results

   

    

 

2.4 Session life cycle control

    <!--在web.xml文件中配置了这个属性,表示在当前的web工程中所创建出来的所有Session对象的生命周期都是20分钟-->
    <session-config>
        <session-timeout>20</session-timeout>
    </session-config>

(1) After the web project is successfully deployed, there will be a project deployment address:

/Users/c/Library/Caches/IntelliJIdea2018.1/tomcat/Tomcat_8_5_32_spring5-txdemo3-javaWeb_3

(2) Open the path in the terminal, find the file web.xml under the path, and find that the life cycle of all Sessions in the web project has been configured.

(3) Of course, we can set this global timeout according to the actual scenario in our web project: configuration in the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>SessionServlet</servlet-name>
        <servlet-class>com.wind.servlet.SessionServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>SessionServlet</servlet-name>
        <url-pattern>/sessionServlet</url-pattern>
    </servlet-mapping>

    <!--在web.xml文件中配置了这个属性,表示在当前的web工程中所创建出来的所有Session对象的生命周期都是20分钟-->
    <session-config>
        <session-timeout>20</session-timeout>
    </session-config>

</web-app>

2.4.1 First: Create a Servlet Processor

package com.wind.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.Method;

/**
    //4.获取Session的默认时长
    //5.设置Session的超时时长=3秒
    //6.设置Session马上销毁
 */
public class SessionServlet extends HttpServlet {

    private static final long serialVersionUID = 3312652355957854184L;

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

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决POST请求中的中文乱码问题,一定要在获取请求参数之前调用才有效
        request.setCharacterEncoding("UTF-8");
        //解决响应中的中文乱码问题
        response.setContentType("text/html; charset=UTF-8");

        String action = request.getParameter("action");
        try {
            //使用反射技术:获取action业务鉴别字符串,获取相应的业务方法
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(new SessionServlet(), request, response);
        } catch (Exception e) {
            System.out.println("SessionServlet error..." + e);
        }
    }

    //测试1:创建session会话对象和获取session会话对象
    private void createOrGetSession(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.创建和获取session会话对象
        HttpSession session = request.getSession();
        //2.判断当前的session会话对象是否是新创建出来的
        boolean aNew = session.isNew();
        //3.获取当前的session会话对象的唯一标识ID值
        String sessionId = session.getId();
        response.getWriter().write("获取了session,它的ID值=" + sessionId + "<br/>");
        response.getWriter().write("这个session是否是新建的=" + aNew + "<br/>");
    }

    //测试2:Session域数据的存储
    private void setAttribute(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.获取Session会话对象
        HttpSession session = request.getSession();
        //2.向Session对象中存储数据
        session.setAttribute("key1", "value1");
        response.getWriter().write("已经向Session中存储了数据<br/>" + session);
    }

    //测试3:Session域数据的获取
    private void getAttribute(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.想要从Session对象中获取的值的key
        String name = "key1";
        //2.使用自己编写的Session工具类获取对应的value
        Object attribute = SessionUtils.getAttribute(name, request);
        //3.输出到客户端展示
        response.getWriter().write("从Session对象中已经找到了想要的数据<br/>" + "key=" + name + "value=" + attribute);
    }

    //4.获取当前web工程项目中的Session对象的默认时长
    private void defaultLife(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int maxInactiveInterval = request.getSession().getMaxInactiveInterval();
        response.getWriter().write("Session的默认时长=" + maxInactiveInterval + "秒");
    }

    /**
     * Session的超时时长是指:客户端向服务器端发送两次HTTP请求之间的最大的时间间隔。
     * 第二次请求和第一次请求之间的时间间隔,一旦超过了这个超市时长,则第一次请求所创建的Session对象也就被销毁了,
     * 在第二次请求中就需要重新创建一个习的Session会话对象,来维护第二次请求的客户端和服务器端之间的关联关系。
     **/
    //5.设置当前Session的超时时长=3秒
    private void setDestroyTime3Miao(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(3);
        response.getWriter().write("设置Session的超时时长=3秒");
    }

    //6.设置当前的Session马上销毁
    private void setDestroyTimeInvalidate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        response.getWriter().write("设置Session马上销毁");
    }
}

2.4.2 Second: Configure the access path in the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>SessionServlet</servlet-name>
        <servlet-class>com.wind.servlet.SessionServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>SessionServlet</servlet-name>
        <url-pattern>/sessionServlet</url-pattern>
    </servlet-mapping>

    <!--在web.xml文件中配置了这个属性,表示在当前的web工程中所创建出来的所有Session对象的生命周期都是20分钟-->
    <!--Session的超时:指定是客户端发给服务器两次请求之间的最大的时间间隔-->
    <session-config>
        <session-timeout>20</session-timeout>
    </session-config>

</web-app>

2.4.3 Third: Write a front-end page-session.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <title>Cookie</title>
    <base href="http://localhost:8080/13_cookie_session/">
    <style type="text/css">
        ul li {
            list-style: none;
        }
    </style>
</head>
<body>
<iframe name="target" width="500" height="200" style="..."></iframe>
<div style="...">
    <ul>
        <li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号是否为新创建)</a></li>
        <li><a href="sessionServlet?action=setAttribute" target="target">Session域数据的存储</a></li>
        <li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a></li>
        <li>Session的生存周期</li>
        <li>
            <ul>
                <li><a href="sessionServlet?action=defaultLife" target="target">Session的默认超时时间</a></li>
                <li><a href="sessionServlet?action=setDestroyTime3Miao" target="target">Session的超时时间设置=3秒超时销毁</a></li>
                <li><a href="sessionServlet?action=setDestroyTimeInvalidate" target="target">Session的超时时间是马上销毁</a></li>
            </ul>
        </li>
        <li><a href="sessionServlet?action=" target="target">浏览器和Session绑定的原理</a></li>
    </ul>
</div>
</body>
</html>

2.4.4 Fourth: Test and Results

    

2.5 The technical inside story of the browser and Session association

2.5.1 Illustration: how the browser and the session object are related at the bottom

2.5.2 Text: how the browser and the session object are related at the bottom

(1) Send the request for the first time:

        (1.1) When the client, that is, the browser, sends a request to the server for the first time, there is no cookie information . In this case, call request.getSession on the server side () method is to directly create  a session this session Session object. At the same time, when the server creates the session object, it will create a cookie object at the same time . The key of the cookie object is always JSESSIONID, and the value is the ID value of the newly created session object, that is: the cookie object and the session The object is already bound . Then, the server will tell the client to do something by storing the cookie data just created in the response object and spit it out to the client.

        (1.2) What do you do? After the browser receives the result of the first request, it will immediately create a cookie object on the client side . The information in this cookie object is the information just returned from the server side (key is JSESSIONID, value is the first request session ID value of the session object created at the time). So far, the client has saved the connection between the client and the server during the session.

        (1.3) Note: This session object is stored in the memory of the server, because a server will be accessed by many clients, so there will be many session objects in the server memory, which are used to save each client Contact with the conversation between the server.

(2) Send the request for the second time (after the end of the first request, initiate the second request without closing the browser):

        (2.1) Because the client already has a cookie object, no matter how many HTTP requests after the first request, the cookie object will be sent to the server with the cookie object in the request header.

        (2.2) After the server receives the subsequent request, when calling the request.getSession() method, it does not re-create a session, but directly finds the previously created session from the server memory through the JSESSIONID in the cookie object After finding the object, the server can directly use the session object . It can be ensured that no matter how many times these subsequent requests, they actually belong to the same session as the first request, and all of them are the same session object, and the data in the session object is all of these Request to share.

(3) Send the request for the third time (after the second request is over, first close the browser, then reopen the browser, and initiate the third request):

        (3.1) After the second request is over, first close the browser, and then reopen the browser, and then initiate the third HTTP request. At this time, the session created on the client during the first request is maintained. The cookie object is destroyed as the browser is closed, then the third request sent by the client will be in a cookieless state . At this time, the server will still call the request.getSession() method after receiving the third request. , It will be found that the client does not carry cookie data, so the server will create a new session object to maintain the relationship between the client and the server. At the same time, when the server creates this new session object, it will At the same time, a new cookie object is created. The key of the new cookie object is always JSESSIONID, and the value is the ID value of the new session object, that is, the new cookie object and the new session object are bound together again. Then, the server will tell the client to save it by storing the new cookie just created in the response and spit it out to the client.

        (3.2) Then, after the browser receives the result of the third request, it will immediately create a cookie object on the client side. The information in this cookie object is the session information just returned from the server side (key is JSESSIONID, value is the ID value of the new session object created in the third request). At this point, a new session information has been saved on the client. This new session information maintains the session information between the client and the server for the third request and subsequent requests (without closing the browser in the case of).

        (3.3) Once the browser is closed, the session information created on the server side cannot be found. Why? Because the cookie object saved on the client side created when the session object was created before is also destroyed when the browser is closed, the next time the client sends a request, the cookie data will not be carried. Naturally, it is also on the server side. The session object that has been created before cannot be found.

(4) The following is actually a repetition of the previous content, so I will not repeat it.

 

 

 

 

Guess you like

Origin blog.csdn.net/cmm0401/article/details/111601608