Session Technology Cookie s and Ession

Cookie s and Ession

1. Session Technology

1.1 Sessions

A session contains multiple requests and responses.

Session: The first time a browser sends a request to a server resource, a session is established until one of the parties disconnects.

1.2 Functions

Share data between multiple requests within a single session.

1.3 Mode

  1. Client Session Technology: Cookie
  2. Server-side session technology: Session

2. Cookie

2.1 Overview

Client Session Technology, Save Data to Client

2.2 Steps to use

  1. Create a cookie object to bind data.

    ​ new Cookie(String name, String value)

  2. Send cookie object

    ​ response.addCookie(Cookie cookie)

  3. Get Cookie s, Get Data

    ​ Cookie[] request.getCookies()

    @WebServlet("/cookieDemo1")
    public class CookieDemo1 extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //1. Create a cookie object
            Cookie cookie = new Cookie("msg", "hello");
            //2. Send cookie s
            response.addCookie(cookie);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
    }
    
    
    @WebServlet("/cookieDemo2")
    public class CookieDemo2 extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //3. Get Cookie s
            Cookie[] cookies = request.getCookies();
            //Get data, traverse Cookies
            if (cookies != null) {
                for (Cookie c : cookies) {
                    String name = c.getName();
                    String value = c.getValue();
                    System.out.println(name+":"+value);
                }
            }
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
    }
    

2.3 Implementation Principles

Based on response header set-cookie and request header cookie implementation.

2.4 cookie details (highlights)

  1. Can't you send more than one cookie at a time?

    Yes,

    You can create multiple objects and send a cookie using the response call to the addCookie method multiple times.

  2. How long do cookie s stay in the browser?

    1. By default, Cookie data is destroyed when the browser is closed.

    2. Persistent storage:

      ​ setMaxAge(int seconds)

       1. **Positive number: will cookie The data is written to a file on the hard disk. Persist storage. cookie Survival time.**
       2. **Negative number: default**
       3. **Zero: Delete cookie information**
      
  3. Can cookie s be saved in Chinese?

    Chinese data cannot be stored directly in cookie s until tomcat8

    After tomcat8, cookie s support Chinese data.

  4. Scope of cookie sharing?

    1. If there are multiple web projects deployed in the same tomcat server, can cookie s be shared among these web projects?

    Cookies cannot be shared by default

    setPath(String path): Sets the scope for cookie s. By default, set the current virtual directory
    2. cookie sharing between different tomcat services?

    setDomain(String path): If the primary domain name is the same, then between servers cookie Can be shared.
    

    setDomain(".baidu.com"), then cookie s in tieba.baidu.com and news.baidu.com can be shared.

  5. What are the features and functions of cookie s?

    1. Cookies store data in client browsers
      1. Browsers have limits on the size of a single cookie (4kb) and on the total number of cookies under the same domain name (20)

    Effect:

    1. Cookies are typically used to store small amounts of less sensitive data.
      1. Complete the server's identification of the client without logging on.

3. cookie case: remember last visit time

  1. Requirements:
    1. Visit a servlet, if it is your first visit, then prompt: Hello, welcome to your first visit.
    2. If it is not your first visit, then Tip: Welcome back, the last time you visited was: Show time string.

  2. Analysis:
    1. Cookies can be used to achieve this
    2. The servlet on the server determines if there is a cookie named lastTime
    1. Yes: It's not your first visit
    1. Response data: Welcome back, your last visit was 11:50:51 June 6, 2021
    2. Write back cookie:lastTime=6 June 2021 11:50:51
    2. No: First visit
    1. Response data: Hello, welcome to your first visit
    2. Write back cookie:lastTime=11:50:51 June 10, 2018

/**
    The servlet on the server determines if there is a cookie named lastTime
     1. Yes: not the first visit
        1. Response Data: Welcome back, your last visit was 11:50:51 June 6, 2021
        2. Write back cookie:lastTime=11:50:51 June 6, 2021
     2. No: First visit
        1. Response data: Hello, welcome to your first visit
        2. Write back cookie:lastTime=11:50:51 June 10, 2018
 */
@WebServlet("/cookieTest")
public class CookieTest extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Set the data format and encoding of the message body of the response
        response.setContentType("text/html;charset=utf-8");
        //1. Get all cookies
        Cookie[] cookies = request.getCookies();
        boolean flag = false;//No cookie is lastTime
        //2. Traverse the cookie array
        if (cookies != null && cookies.length > 0) {
            for (Cookie c :cookies) {
                //3. Get the name of the cookie
                String name = c.getName();
                //4. Determine if the name is: lastTime
                if ("lastTime".equals(name)) {
                    //This cookie is available, not the first time you visit it
                    flag = true;//Cookies with lastTime
                    //Set cookie value
                    //Get the string of the current time, reset the value of the cookie, and resend the cookie
                    Date date = new Date();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
                    String str_format = simpleDateFormat.format(date);
                    System.out.println("Before encoding:"+str_format);
                    //URL encoding
                    str_format = URLEncoder.encode(str_format,"utf-8");
                    System.out.println("After encoding:"+str_format);
                    c.setValue(str_format);
                    //Set cookie lifetime
                    c.setMaxAge(60*60*24*30);//One month
                    //Resend cookie s
                    response.addCookie(c);

                    //Response data
                    //Get cookie value, time
                    String value = c.getValue();
                    System.out.println("Before decoding:"+value);
                    //URL Decoding
                    value = URLDecoder.decode(value,"utf-8");
                    System.out.println("After decoding:"+value);
                    response.getWriter().write("<h1>Welcome back, your last visit was:"+value+"</h1>");

                    break;
                }
            }
        }

        if (cookies == null || cookies.length == 0 || flag == false) {
            //No, first visit
            //Set Cookie value
            //Get the string of the current time, reset the value of the cookie, and resend the cookie
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
            String str_format = simpleDateFormat.format(date);
            System.out.println("Before encoding:"+str_format);
            //URL encoding
            str_format = URLEncoder.encode(str_format,"utf-8");
            System.out.println("After encoding:"+str_format);

            Cookie cookie = new Cookie("lastTime", str_format);
            cookie.setValue(str_format);
            //Set cookie lifetime
            cookie.setMaxAge(60 * 60 * 24 * 30);//One month
            response.addCookie(cookie);

            response.getWriter().write("<h1>Hello, welcome to your first visit</h1>");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

4.Session

4.1 Concepts

Server-side session technology, which shares data between multiple requests for a second session and stores the data in server-side objects. HttpSession

4.3 Getting Started

  1. Get the session object:

    ​ HttpSession session = request.getSession();

  2. Using the HttpSession object:

    ​ Object getAttribute(String name)

    ​ void setAttribute(String name, Object value)

    ​ void removeAttribute(String name)

4.4 Principle

session implementation is Cookie dependent

4.5 Details

  1. When the client shuts down, the server does not shut down. Is it the same session to get two sessions?

    By default. No

    If the same is required, you can create a cookie with the JSESSIONID key to set the maximum lifetime for the cookie to persist.

    //Expect session s to be the same when the client shuts down
    Cookie cookie = new Cookie("JSESSIONID",session.getId());
    cookie.setMaxAge(60*60);
    response.addCookie(cookie);
    
  2. Client does not shut down. After server shuts down, do you get the same session twice?

    Not the same, but make sure the data is not lost.

    org.apache.catalina.session.StandardSessionFacade@1bb64cbb
    org.apache.catalina.session.StandardSessionFacade@6bd8cb0e
    

    Passivation of session:

    Serialize the session object to the hard disk before the server shuts down normally.

    Activation of session:

    Convert the session file into an in-memory session object after the server starts up normally.

  3. When was session destroyed?

    1. Server shutdown

    2. The session object calls invalidate().

    3. session default expiration time of 30 minutes

      Selective Configuration Modification

      <session-config>
      	<session-timeout>30</session-timeout>
      </session-config>
      

4.6 Features

  1. Session stores data for multiple requests for a session and is server-side.
  2. Sessions can store data of any type and size.

The difference between session and cookie:

  1. session stores data on the server side, cookie s store data on the client side

  2. session has no data size limit, cookies have.

  3. session data is secure, cookies are not.

    <session-config>
    	<session-timeout>30</session-timeout>
    </session-config>
    ```
    

4.6 Features

  1. Session stores data for multiple requests for a session and is server-side.
  2. Sessions can store data of any type and size.

The difference between session and cookie:

  1. session stores data on the server side, cookie s store data on the client side
  2. session has no data size limit, cookies have.
  3. session data is secure, cookies are not.

Tags: Java Operation & Maintenance server

Posted on Thu, 11 Nov 2021 11:01:11 -0500 by friendlylad