Session Cookie&&Session

Table of contents

1. Cookie Technology

1 The concept of cookies

2 The role of cookies

3 Application Scenarios of Cookies

4 Introduction to Cookies

5 Timeliness of cookies

6 Cookie path

Two Session Technology

1 session overview

2 Session entry case

3 Session working mechanism

4 Timeliness of Session


1. Cookie Technology

1 The concept of cookies

        Cookie is a client-side session technology. It is a small piece of data stored in the browser by the server. Every time the browser visits the server in the future, it will carry this small piece of data to the server.

2 The role of cookies

  1. Store data in the browser

  2. Carry the data stored in the browser to the server

3 Application Scenarios of Cookies

        1. Remember username

        When we enter the user name in the user name input box, the browser records the user name, and when we visit the login page next time, the user name is automatically filled into the user name input box.

        2. Save the playback progress of the movie

        When playing a movie on a web page, if you exit the browser midway, download and open the browser to play the same movie, it will automatically jump to the progress of the last exit, because the playback progress will be saved to cookie

4 Introduction to Cookies

① target

Realize sharing data between ServletDemo01 and ServletDemo02, requiring sharing within the scope of the session domain

② Cookie-related APIs

  • Create a Cookie object (cookies can only save string data. And can not save Chinese)

new Cookie(String name,String value);
  • Write the cookie back to the browser

response.addCookie(cookie); 
  • Get all cookies brought by the browser:

request.getCookies() ; //得到所有的cookie对象。是一个数组,开发中根据key得到目标cookie
  • cookie API

cookie.getName() ; //返回cookie中设置的key
cookie.getValue(); //返回cookie中设置的value

③ ServletDemo01 code

Create Cookie data in ServletDemo01 and respond to the client

public class ServletDemo01 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 创建一个cookie对象,用于存放键值对
        Cookie cookie = new Cookie("cookie-message","hello-cookie");

        //2. 将cookie添加到response中
        //底层是通过一个名为"Set-Cookie"的响应头携带到浏览器的
        response.addCookie(cookie);
    }
}

 

④ Browser sends request with Cookie

There is no need for us to operate here. When the browser sends a request to the server, it will automatically carry the cookie to the server through the request header.

 

 ⑤ ServletDemo02 code to obtain cookie data

public class ServletDemo02 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 从请求中取出cookie
        //底层是由名为"Cookie"的请求头携带的
        Cookie[] cookies = request.getCookies();

        //2. 遍历出每一个cookie
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //匹配cookie的name
                if (cookie.getName().equals("cookie-message")) {
                    //它就是我们想要的那个cookie
                    //我们就获取它的value
                    String value = cookie.getValue();
                    System.out.println("在ServletDemo02中获取str的值为:" + value);
                }
            }
        }
    }
}

5 Timeliness of cookies

If we do not set the timeliness of the cookie, by default the validity period of the cookie is within the scope of one session, we can use the setMaxAge() method of the cookie to make the cookie persistent and save it to the browser

  • session level cookies

    • The server does not explicitly specify the lifetime of the cookie

    • On the browser side, cookie data exists in memory

    • As long as the browser is still open, the cookie data is always there

    • When the browser is closed, the cookie data in the memory will be released

  • persistent cookie

    • The server side explicitly sets the lifetime of the cookie

    • On the browser side, the cookie data will be saved to the hard disk

    • The time that cookies exist on the hard disk is controlled according to the time limited by the server, and is not affected by the closing of the browser

    • The persistent cookie will be released when the preset time is reached

cookie.setMaxAge(int expiry)The parameter unit is seconds, indicating the persistence time of the cookie. If the parameter is set to 0, it means that the cookie saved in the browser will be deleted

6 Cookie path

If you surf the Internet for a long time, many cookies will be saved locally. For browsers, it is not possible to bring all cookies every time when accessing Internet resources. The browser will use the path attribute value of the cookie to compare it with the currently visited address to decide whether to carry the cookie.

We can set the cookie's path by calling the cookie's setPath() method

Two Session Technology

1 session overview

        session is a server-side technology. The server opens up a memory space for each browser, namely the session object. Since the session object is unique to each browser, user records can be stored in the session object

2 Session entry case

① target

Realize sharing data between ServletDemo01 and ServletDemo02, requiring sharing within the scope of the session domain

② Session API introduction

  • request.getSession(); Get the session (if the first call is actually to create a session, after the first time, use the sessionId to find the session)

  • Object getAttribute(String name) ; get the value

  • void setAttribute(String name, Object value) ; store value

  • void removeAttribute(String name) ; remove value

③ Store data in the Session domain object in ServletDemo01

public class ServletDemo01 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取Session对象
        HttpSession session = request.getSession();
        //2. 往Session对象中存入数据
        session.setAttribute("session-message","hello-session");
    }
}

 ④ Obtain data from the Session domain object in ServletDemo02

public class ServletDemo02 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取Session对象
        HttpSession session = request.getSession();
        //2. 往Session对象中存入数据
        String message = (String)session.getAttribute("session-message");
        System.out.println(message);
    }
}

3 Session working mechanism

Premise: The browser accesses the server normally

  • The request.getSession() method is not called on the server side: nothing will happen

  • The server calls the request.getSession() method

    • The server side checks whether the current request carries the JSESSIONID Cookie

      • Yes: Find the corresponding HttpSession object on the server side according to JSESSIONID

        • Can be found: return the found HttpSession object as the return value of the request.getSession() method

        • Not found: The server creates a new HttpSession object as the return value of the request.getSession() method

      • None: Create a new HttpSession object on the server side as the return value of the request.getSession() method

// 1.调用request对象的方法尝试获取HttpSession对象
HttpSession session = request.getSession();

// 2.调用HttpSession对象的isNew()方法
boolean wetherNew = session.isNew();

// 3.打印HttpSession对象是否为新对象
System.out.println("wetherNew = " + wetherNew+"HttpSession对象是新的":"HttpSession对象是旧的"));

// 4.调用HttpSession对象的getId()方法
String id = session.getId();

// 5.打印JSESSIONID的值
System.out.println("JSESSIONID = " + id);

4 Timeliness of Session

① Why does Session have to set a time limit

After a large number of users, a lot of Session objects should be created accordingly. If you blindly create and do not release, the memory on the server side will be exhausted sooner or later.

② Difficulties in setting time limits

From the server side point of view, it is difficult to know exactly the actions like closing the browser. And even if the browser has not been closed, it does not mean that the user is still using it.

③ The server sets the maximum idle time for the Session object

  • Default: 1800 seconds

The mechanism by which the maximum idle time takes effect is as follows:

// ※测试时效性
// 获取默认的最大闲置时间
int maxInactiveIntervalSecond = session.getMaxInactiveInterval();
System.out.println("maxInactiveIntervalSecond = " + maxInactiveIntervalSecond);

// 设置默认的最大闲置时间
session.setMaxInactiveInterval(15);

 ⑤ Force Session to expire immediately

session.invalidate();

Guess you like

Origin blog.csdn.net/rbx508780/article/details/127495858