1. What are Session and Cookie

1.1 Concept Understanding

To understand what sessions and cookies are, it’s important to understand the following concepts.

1.1.1 Stateless HTTP protocol

Protocol: refers to the rules or rules that must be followed by two computers in a computer communication network to communicate.

Hypertext Transfer Protocol (HTTP) : is a communication protocol that allows hypertext Markup Language (HTML) documents to be transferred from a Web server to a client’s browser.

HTTP is a stateless protocol. Once the data exchange is complete, the connection between the client and server is closed and a new connection needs to be established to exchange data again. This means that the server cannot track the session from the connection.

1.1.2 Session Tracing

Session: refers to the sequence of actions a user takes after logging into a web site, such as browsing for items to add to the cart and making a purchase. Session tracing is a common technique used in Web applications to track a user’s entire Session. Common Session tracking techniques are Session and Cookie. Session identifies users by recording information on the server, and Cookie identifies users by recording information on the client.

1.2 the Cookie

Because HTTP is a stateless protocol, the server has no way of knowing the identity of the client from the network connection alone. User A buys an item and puts it in the shopping cart. When user A purchases the item again, the server cannot determine whether the purchase belongs to user A’s session or user B’s session. What to do? Just issue a pass to the clients, one for each, and whoever accesses must bring their own pass. So the server can identify the client from the pass. That’s how cookies work.

A Cookie is actually a small piece of text information. The client requests the server, and if the server needs to record the user state, it issues a Cookie to the client browser using response. The client saves the Cookie.

When the browser requests the site again, the browser submits the requested URL along with the Cookie to the server. The server checks the Cookie to identify the user’s state. The server can also modify the contents of the Cookie as needed.

1.2.1 Session Cookie and Persistent Cookie If the expiration time is not set, it indicates that the lifetime of the Cookie is during the browser session, and the Cookie disappears when the browser window is closed. Cookies with a lifetime of a browser session are called session cookies. Session cookies are generally not stored on hard disk but in memory, although this behavior is not regulated by the specification.

If the expiration time is set, the browser saves cookies to hard disk, closes the browser and opens the browser again. These cookies remain valid until the expiration time is exceeded. Cookies stored on the hard disk can be shared between different processes in the browser. This is called a persistent Cookie.

1.2.2 Cookie is non-transdomainable

That is to say, the browser will not visit Baidu with Google’s cookie

1.3 the Session

Session is another mechanism for recording the client’s state, except that cookies are stored in the client browser, while sessions are stored on the server. When the client browser accesses the server, the server records the client information on the server in a form called a Session. The client browser only needs to look up the client’s status from the Session when revisiting. Each user accessing the server establishes a session and is automatically assigned a SessionId, which identifies the unique identity of the user.

1.3.1 Two questions

1) How do I automatically bring the SessionId to the server on every request?

If you want to set up a session with the user, you can return a unique cookie when the user is successfully authorized. When a user makes a request again, the browser automatically appends the user’s SessionId to the HTTP header (this is an automatic feature of the browser, so the user doesn’t notice and the developer doesn’t have to do anything about it), and when the server processes the request, it returns the result to the user with the SessionId.

2) Store the information you need.

The server uses the SessionId as the key to read and write the corresponding value, which achieves the purpose of maintaining session information.

1.3.2 Session Creation

When the program needs to create a session for a client request, the server first checks whether the client request contains the sessionId. If it contains the sessionId, it indicates that the client has created a session before. The server retrieves the session based on the session ID and uses it. If the client request does not contain a session ID, a session is created for the client and a session associated with the session is generated

The sessionId of the link, the value of the sessionId is a string that is neither repeated nor easily found to mimic, and the sessionId will be returned to the client for saving in this response.

1.3.3 disable cookies

If cookies are disabled on the client, there are usually two ways to implement a session without relying on cookies.

1) URL rewrite. Append the sessionId directly to the URL path.

2) Form hiding field. The server automatically modifies the form to add a hidden field so that the sessionId can be passed back to the server when the form is submitted.

Such as:

<form name="walking-form" action="/xxx/xxx"> 
    <input type="hidden" name="JSessionId" value="NaOw3vjFW75aKnsF2C2HmdnV9LZcEbzWoWiBdHnLerjQ99zmpQng! - 142002807"> 
    <input type="text"> 
</form>
Copy the code

For a single server with multiple websites (same parent domain and different sub-domains), what we need to solve is the sharing of sessionids from different websites. Because the domain names are different (aaa.walking.com and bbb.walking.com) and the sessionids are stored in their respective cookies, the server will assume that the visits to the two sub-sites are from different sessions. The solution is to change the domain name of cookies to the parent domain name to achieve the purpose of cookie sharing, so as to achieve the sharing of sessionIDS (non-server cluster session sharing). The downside is that cookie information is also shared between sub-sites.

1.4 Application Scenarios

Login site, enter the user name and password login, the next day to open a lot of cases directly opened. One mechanism used at this point is cookies. Session One scenario is a shopping cart, after adding items, the client can know which items are added, and the server can tell what is added, so it also needs to store some information so it uses the session.

2. How to operate Session

Sessions provide a lot of convenience in Java Web development, and they are maintained between the browser and the server. In traditional Java web development, by implementing our javax.mail. Servlet. The servlet interface or inherit javax.mail. Servlet. HTTP. HttpServlet to implement the client and server interact with the HTTP protocol.

2.1 API for operating Session

The operations on the Session are as follows:

@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpSession session = request.getSession();
    
    session.setAttribute("userName"."walking");// Set the properties
    session.setMaxInactiveInterval(30*60);// Expiration time in seconds
    session.getCreationTime();// Get the session creation time
    session.getLastAccessedTime();// Get the last interaction time with the server
    String id = session.getId();/ / get sessionId
    int timeout = session.getMaxInactiveInterval();// Get the session expiration time
    session.invalidate();/ / the destruction of the session
}
Copy the code

There is a time limit for the client and server to maintain user information. Because the client did not interact with the server for a long time (sleep time), the session is considered to have expired. The server destroys the session, and the previous session does not exist when the client interacts with the server again. This is the expiration of the session.

2.2 Setting the Session Expiration Time

2.2.1 Setting the Session expiration time in traditional Web Projects

1. Set session-config in web. XML

As follows:

<session-config>
      <session-timeout>2</session-timeout>
</session-config>
Copy the code

That is, the maximum interval between two consecutive interactions between the client and the server is two minutes, after which the value obtained by session.getAttribute() is empty. The original session has been destroyed, so fetching the property values from the new session will be empty.

In /conf/web.xml of Tomcat

Session-config: the default value is 30 minutes

<session-config>
     <session-timeout>30</session-timeout>
</session-config>
Copy the code

3. Set in the Servlet

HttpSession session = request.getSession();
session.setMaxInactiveInterval(60);// The unit is seconds
Copy the code

2.2.2 Setting the Session expiration time in the SpringBoot project

2.3 illustrates

1. Priority: API Settings > Program /web. XML Settings > Tomcat/conf/web. XML Settings in the Servlet

2. If the session times out (the interval between the current session and the last session is longer than the maximum interval of inactivity), that is, the last session ends, but a new session is generated between the server and the client. All the values of the previous session attributes are lost, and a new sesssionId is generated

3. An effective client and server session (session timeout), every visit to the same sessionId, set up a session. If the code setMaxInactiveInterval () value, then the session one of the biggest inactivity time interval will be modified and applied to the new value.

4.Session destruction (representing the end of the Session period) : The Session is destroyed when the session.invalidate () method is called during a request period. Or the session is automatically destroyed after the session times out. Or the client closes the browser

<% @page session=”false”%> The JSP does not automatically perform request.getSession() to retrieve the session.

3. Operating Cookie

3.1 The server Operates cookies

Said earlier, the client request every time the server will put a cookie information in the head of the header information, we can through it. The getCookies () method to obtain all the cookie object, Cookies are returned to the client via the addCookie method of the HttpServletResponse object.

The specific operation API is as follows:

Cookie[] cookies = request.getCookies();// The request object gets all cookies
for (Cookie cookie : cookies) {
    String name = cookie.getName();//cookie name
    String value = cookie.getValue();//cookie value
    String domain = cookie.getDomain();/ / domain name
    int maxAge = cookie.getMaxAge();// Expiration time
    boolean secure = cookie.getSecure();// The browser returns true for sending cookies over security protocols
    String comment = cookie.getComment();/ / description
    int version = cookie.getVersion();/ / version
    // All attributes except name have corresponding set methods

    boolean httpOnly = cookie.isHttpOnly();/ / whether the Httponly
    cookie.setHttpOnly(true);// Set the Httponly value
}
/ / new cookie object
Cookie cookie = new Cookie("userName"."walking");
cookie.setPath("/");
cookie.setMaxAge(60*30);/ / for 30 minutes
response.addCookie(cookie);// Write back to the client browser
Copy the code

3.2 Front-end operation cookie

Front-end creation sets cookies

/** * Create and set cookie * @param name Cookie name * @param Value Cookie value * @param Expires time Ms Default 30 minutes */
function Setcookie(name, value, expires) {
    // Set the Cookie with name and value
    expires = expires || 30* 60 * 1000;
    var expdate = new Date(a);// Initialization time
    expdate.setTime(expdate.getTime() + expires);   / / time
    / / the document. The cookie = value + name + "=" + "; path=/"; The time is optional, but the path must be filled in.
    // Because the default path of JS is the current page, if not, this cookie only works on the current page! ~
    document.cookie = name + "=" + value + "; expires=" + expdate.toGMTString() + "; path=/";
}
Copy the code

The front end gets the cookie property value

/** * Obtain the value of the corresponding cookie attribute * @param c_name Cookie attribute name * @returns {string} cookie value */
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if(c_start ! =- 1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == - 1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end)); }}return "";
}
Copy the code

4. To summarize

1. Cookie data is stored in the client’s browser, and session data is stored on the server.

2. Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies.

3. Sessions are stored on the server for a certain period of time. Cookies should be used to reduce server performance when the number of accesses increases.

4. The data saved by a single cookie cannot exceed 4K. Many browsers limit the maximum number of cookies saved by a site to 20.

5. Important information such as login information can be stored as session, and other information can be stored in cookies if necessary.

6, in the process of program development, we can check the SessionID (Session attribute value, non-Httpservlet environment development can also be replaced by other Key values) in the client every time the server interaction, for Session management.

The original link