Session is actually divided into client Session and server Session

When a user first establishes a connection with the Web server, the server issues a SessionID to the user as an identifier. A SessionID is a random string of 24 characters. Each time the user submits a page, the browser submits the SessionID in the HTTP header to the Web server, so that the Web server can distinguish which client is currently requesting the page. The SessionID is stored in the client and belongs to the client Session. The client Session is stored as a cookie by default, so when users disable cookies, the server does not get the SessionID. In this case, we can store the client Session as a URL. The SessionID is written directly into the URL, which is not often used.

How to generate a SessionID? By whom? Where do you keep it?

The purpose of the Session object:

The Session object stores properties and configuration information required for a specific user Session. This way, variables stored in the Session object will not be lost when the user jumps between Web pages of the application, but will persist throughout the user Session. When a user requests a Web page from an application, the Web server automatically creates a Session object if the user does not already have a Session. When a session expires or is abandoned, the server terminates the session. One of the most common uses of the Session object is to store user preferences. For example, if the user indicates that he does not like to view graphics, that information can be stored in the Session object.

The sessionId is the key of a session. When the browser accesses the server for the first time, a session is generated on the server side and a sessionId corresponds to it. The session IDS generated by Tomcat are called jsessionids. The session is created when accessing getSession(True) of the Tomcat server HttpServletRequest. The Tomcat ManagerBase class provides methods to create session-id: Random number + time + JVMID; It is stored in the server’s memory. Tomcat’s StandardManager class stores sessions in memory and can persist them to file, database, memcache, Redis, etc. The client only saves the sessionID into the cookie, but does not save the session. The session destruction can only be done by invalidate or timeout. Closing the browser does not close the session.

Will sessions be deleted due to browser shutdown?

Cookies are divided into in-memory cookies (also known as in-process cookies) and hard disk cookies. Most Session mechanisms use in-process cookies to store Session ids. When you close the browser, the Session disappears automatically. Cookies in the process disappear, and the Session ID disappears. When connecting to the server again, the original Session cannot be found. Of course, we can click on the next automatic login when we log in, such as CSDN’s “Remember me for a week,” or our shopping cart information can still be used when we switch browsers. In this case, the session-ID is stored in the Cookie on the hard disk until it expires.

Session creation in Tomcat

ManagerBase is the base class of all session management utility classes. It is an abstract class that all classes that implement session management inherit from this class. This class has a protected method that creates a session ID value: ManagerBase (Tomcat session ID is generated by a random number + time + JVM ID. The JVM ID will be calculated according to the hardware information of the server, so the ID value of different JVMS is unique.)

The StandardManager class is the default session management implementation class in the Tomcat container and stores session information in memory on the server where the Web container resides.

PersistentManagerBase also inherits the ManagerBase class, which is the base class for all persistent session information. PersistentManager inherits PersistentManagerBase, For persistent sessions, Tomcat also provides the StoreBase abstract class, which is the base class for all persistent sessions. In addition, Tomcat also provides file storage FileStore and data storage JDBCStore two implementations.

Session is a server solution to the stateless problem of HTTP protocol. It can make a series of interactions between the client and the server become a complete transaction, and make the website become a software in a real sense.

The difference between session cookies and persistent cookies

If the expiration time is not set, it means that the cookie lifetime is during the browser session. As soon as the browser window is closed, the cookie disappears. Cookies with a lifetime of browsing sessions are called session cookies. Session cookies are generally stored in memory rather than on hard disk. If an expiration date is set, the browser saves cookies to hard disk, closes the browser and opens it again. These cookies remain valid until the expiration date is exceeded. Cookies stored on the hard disk can be shared between different browser processes, such as two IE Windows. For cookies stored in memory, different browsers treat them differently.

Precautions for Cookie/Session usage

  1. Cookie size is limited to 4K
  2. Cookies cannot cross browsers
  3. Cookie does not support Chinese
  4. Data with high security should be stored in session, because cookies stored on the client can always be easily obtained by criminals
  5. Do not store user data in a session if the site has a large number of visits, because storing one session per user will cause great pressure on the server

Several ways to store a SessionID

  1. The session-ID can be saved using cookies, so that the browser can automatically send the session-ID to the server according to the rules during the interaction.
  2. Since cookies can be artificially disabled, there must be other mechanisms to pass session-ID back to the server even if cookies are disabled, a technique often used is calledThe URL rewriteTo append the session-ID to the URL path (the network must include the session-ID at the end of every possible URL path requested by a client if the network remains in state throughout the interaction). There are two ways to append the session-ID:
    • One is as additional information to the URL path
    • The other is to append the URL as a query string
  3. Another technique is called form-hiding fields. The server automatically modifies the form to add a hidden field so that it can pass the session-ID back to the server when the form is submitted.

When is the Session created

A common mistake is to think the session with the client to access when it was created, but the fact is that until a server end program (such as servlets) calls it. GetSession (true) such a statement will be created.

When the Session was deleted

Sessions are deleted in the following cases:

  1. Program callsHttpSession.invalidate()
  2. The interval between the last session-ID sent from the client and the last session-ID sent from the client exceeded the maximum validity period of the session. Procedure
  3. The server process is stopped

Note again that closing the browser only causes the store to be stored inClient browser memoryIf the session cookie is invalid, the session object on the server will not be invalid.

GetSession ()/getSession(True) and getSession(false)

  • getSession() / getSession(true): Returns a session if it exists. Otherwise, create a new session and return the object
  • getSession(false): Returns a session if it exists. Otherwise, no new session is created and null is returned

Use isNew() to determine if a user is old or new

Public Boolean isNew() method: Returns true if the session has not already had any contact with the client (browser). This is usually because the session was created and not caused by an incoming client request. But if isNew() returns false, it simply means that they have accessed the Web application before, not that they have accessed our servlet or JSP page. Because sessions are user-specific, it is possible that a session has been created on every page previously visited by the user. So isNew() is false only means that the user has previously accessed the Web application. The session can be created from the current page or from the page that the user has previously accessed. The correct way is to determine whether a particular key exists in a session and whether its value is correct.

Do Session cookies and Session objects have the same life cycle?

When the user closes the browser, the session cookie disappears, but the session object remains on the server.

Does the Session object disappear as soon as you close the browser?

The application usually sends a command to delete the session when the user logs off, but the browser never actively notifies the server that it is closing before closing, so the server never has a chance to know that the browser has closed. The server keeps the session object until it is inactive beyond the specified interval. This is because most session mechanisms use session cookies to store the session-ID. The session-ID disappears when the browser is closed and the original session cannot be found when the server is connected again. If the cookie set by the server is saved to the hard disk, or the HTTP request header sent by the browser is rewritten in some way to send the original session-ID to the server, the original session can still be found when the browser is opened again. It is precisely because closing the browser does not cause the session to be deleted that the server sets an expiration date for the session. When the time has passed since the client last used the session, the server can assume that the client has ceased to be active. Delete session to save storage space.

Therefore, we can draw the following conclusions: Closing the browser will only make the session cookie in the memory of the browser disappear, but it will not make the session object saved on the server disappear, nor will it make the persistent cookie saved on the hard disk disappear.

Session Sharing Problem

In order to improve the security and concurrency of current Internet websites, the number of servers deployed on the server side is usually greater than or equal to two. The services provided by multiple servers are equivalent, but different servers must have different Web containers. As we know from the above description, session implementation mechanisms are all internal mechanisms in the Web container, which results in different session ID values generated in A Web container. Therefore, when A request is sent to server A and the browser receives A response, What the client saves is the ID of the session generated on server A. When another request is sent to server B, the Web container on server B cannot recognize the ID of this session, let alone the recorded information of this sessionID. At this point, session synchronization between two different Web containers is required. Generally, the websites of large Internet companies are composed of independent channels. For example, baidu, which we commonly use, has Baidu Search, Baidu Music, Baidu Baike and so on. I believe that they will not assign all these different channels to a development team, and each channel should be an independent development team. Because each channel application is a separate Web application, there is a problem of session synchronization across sites. Single sign-on (SSO) solutions can be used for cross-site logins, but session sharing across sites is still an unavoidable problem regardless of the solution.

Single Sign On

Single sign-on, or SSO for short, is one of the more popular solutions for enterprise business integration. SSO is defined as one login in multiple applications that allows users to access all trusted applications.

An overview of the

In the early days, a company might have only one Server, but gradually there were more servers. Each Server must be logged in and logged out one by one. The user experience is bad! You can imagine, on douban to log in douban FM, Douban reading, Douban movies, Douban diary… It really breaks you down. We want a different login experience: a service under an enterprise only needs to be registered once, logged in once, logged out once, how to do that?

Once registration: once registration is not difficult, just want to synchronize user information between the Server on the line? In fact, the management of user information is the real difficulty of SSO, but as a beginner, our difficulty lies in the realization of SSO technology!

Once logged in and once logged out: Looking back at the story of the average store, what is the key to staying logged in? Logger? That piece of paper called cookie? An ID written on a piece of paper? It’s the information that’s recorded in the session and that ID, so cookies are not just a tool for recording ids. The client holds the ID and the server holds the session, both of which are used to maintain the login state. The client needs to use the ID as the credential, while the server needs to use the session to verify the validity of the ID (the ID may be expired, the corresponding information may be forged, and the corresponding client under the ID has not been authenticated yet). However, session is unique to each server at the beginning. Douban FM has its own session, douban reading has its own session, and the cookie that records THE ID cannot be cross-domain. Therefore, we want to achieve a login and a logout, just need to find a way to make each server share a session information, so that the client can hold the ID under each domain name. Further, as long as each server gets the same ID, there is a way to check the validity of the ID and get the user information corresponding to the ID, that is, to check the ID.

implementation

The server side

In terms of how the server cluster generates and verifies ID, there are roughly two ways:

  • “Shared Cookie” : This is the shared session method mentioned above. I prefer to call it “shared session”. In essence, cookies are just the medium for storing session-IDS, which can also be placed in the URL of each request. After all, the session mechanism was originally a one-server, one-session mechanism, so it’s a bit strange to have sessions shared by all servers.
  • Sso-token mode: ** Because the shared session mode is not secure, we no longer use session-ID as the identity identifier. ** We generate another Token and name it sso-token (or Ticket). This Token is unique to the entire server cluster, and all server clusters can verify this Token and get information about the user behind the Token.

The browser

There is another crucial step in single sign-on that has nothing to do with how the server validates the token. The earliest “shared session” method or the present “token” method is used. When the identity is sent to the browser, there is a problem: how can the browser store and share the identity to other domain names after the user successfully logs in and obtains the token (or session-ID)? The same domain name is very simple, save the token in the cookie, set the cookie path to the top-level domain name, so that all subdomains can read the token in the cookie. This is how cookies are shared. For example: Google, google.com is its top-level domain, mail.google.com for the email service and map.google.com for the map service are its subdomains. But what about when you cross domains? Google also has a domain name, youtube.com.

Cookie cross-domain issues: blog.csdn.net/chou_out_ma…

Domain and Path of Cookie attributes

Cookies have two important properties: The domain and path domain tell the browser the domain name of the cookie to be added. If the domain name is not specified, it defaults to the current domain name. For example, the default domain name for cookies added by accessing www.vinceruan.info is www.vinceruan.info, The domain name of the cookie generated by accessing blog.vinceruan.info is blog.vinceruan.info. path tells the browser the current path of the cookie to be added. If it is not specified clearly, it defaults to the current path. Such as by visiting www.vinceruan.info/java/hotspo. Add the default path is/Java/cookies, through blog. Vinceruan. Info/Java/hotspot. The cookie path is generated HTML/Java /.

Technical solutions to solve session-related problems

As mentioned above, there are two problems with sessions:

  1. Session storage should be independent of both the Web container and the server on which the Web container is deployed
  2. How to perform efficient Session synchronization

Before addressing these issues, let’s first consider how sessions are stored efficiently: in memory, in files, or in a database? Both files and databases are stored by storing session data on hard disks. The I/O operation is far less efficient than data in memory. Therefore, it is not advisable to store session data in memory.

So the best solution is to useDistributed cache technologyFor example, memcached and Redis can be used to store session information separately

🤪 The above content has carried on some expansion to the original text

🔗 original link:Blog.csdn.net/java_faep/a…