How the session Works

Source: Internet
Author: User

How the session works
term Session 
in my experience, the term "session" is probably second only to transaction, and more interestingly, the meaning of transaction and the session in some contexts is the same.

Session , Chinese is often translated into a conversation, its original meaning refers to the beginning and end of a series of actions/messages, such as the phone from the pick up the phone to dial to hang up the phone in the middle of a series of processes can be called a session. Sometimes we can see the words "during a browser session, ...", the word for conversation here is its original meaning, which means to open from a browser window to close this period. The most confusing is the "User (client) during a session "in this sentence, it may refer to a series of actions by a user (typically a series of actions related to a specific purpose, such as the process of logging out of an online shopping from login to purchase to checkout), sometimes referred to as a transaction), but sometimes it may just be a connection, or it may mean meaning, where the difference can only be inferred by context.

when the term session is associated with a network protocol, however, itThe implication is that " connection-oriented" and/or "hold State" are two meanings, "connection-oriented" refers to the communication between the two parties before the communication to establish a channel,such as phone calls, until the other side of the phone communication to start, and this is the opposite of the letter, when you send out the message you can not confirm the other person's address is correct, communication channels may not be able to establish, but for the sender, the communication has begun. "Hold state" means that the party of communication can associate a series of messages, so that the message can be interdependent, such as a waiter can recognize the return of the old customers and remember the last time the customer owed a money in the store. Examples of this type are "a TCP session" or "a POP3 session."

In the era of the development of Web server, the semantics of the session in the context of web development has a new extension, which means a kind of solution to maintain state between client and server. Sometimes SESsion is also used to refer to the storage structure of this solution, such as "Keep XXX in Session". Because the various languages used for Web development provide support for this solution to a certain extent, the session is also used to refer to the solution of the language in a particular language context, For example, often the javax.servlet.http.HttpSession provided in Java abbreviated as a session.

Given that this confusion has not changed, the use of the term session in this article will vary depending on the contextplease pay attention to distinguish.
in this article, using the Chinese "browser session" to express the meaning, using the "session mechanism" to express the meaning, using "session" to express the meaning, using the specific "HttpSession" to express the meaning

HTTP protocol and status hold 
The HTTP protocol itself is stateless , which is consistent with the HTTP protocol's original purpose, the client simply needs to request to the server to download some files, both the client and the server do not need to record each other's past behavior, each request is independent , like the relationship between a customer and a vending machine or an ordinary (non-membership) hypermarket.

yet clever (or greedy?) People quickly discovered that providing some on-demand dynamic information would make the web more useful, like adding on-demand functionality to cable TV. This demand on the one hand, forcing HTML to gradually add the form, script, Dom and other client behavior, on the other hand on the server side of the CGI specification in response to the client's dynamic request, as a transport carrier HTTP protocol also added file upload, cookie these features. The purpose of the cookie is to resolve the HTTP protocol's stateless flaws in the efforts made. The subsequent session mechanism is another solution for maintaining state between the client and the server.

Let's use a few examples to describe athe difference between the next cookie and the session mechanism. I used to go to a coffee shop to drink 5 cups of coffee free of charge for a cup of coffee concessions, but a one-time consumption of 5 cups of coffee is very small, then need away to record the amount of money a customer consumes. Imagine the fact that there are several options below: 
1, the shop clerk is very strong, can remember each customer's consumption quantity, as long as the customer walked into the coffee shop, the clerk knew how to treat. This approach is the protocol itself that supports the state .
2, issued to customers a card, the above record the amount of consumption, there is generally a valid period. If the customer presents this card each time it is consumed, the consumption will be linked to the previous or subsequent consumption. This practice is to keep the state on the client .
3, issued to the customer a membership card, in addition to the card number of what information is not recorded, each time the consumer, if the customer presented the card, the shop clerk in the store records found this card number corresponding record add some consumer information. This is done by keeping the state on the server side .

since the HTTP protocol is stateless and is not expected to be stateful due to various considerations, the next two scenarios become a realistic choiceSelect. In particular, the cookie mechanism takes the form of a client-sideThe session mechanism uses a scenario that maintains state on the server side. We also see that the use ofThe client also needs to save an identity on the server , so the session mechanism can It is possible to use the cookie mechanism to achieve the purpose of preserving the identity , but in fact it has other options.

Understanding Cookie Mechanisms 
The basic principle of the cookie mechanism is as simple as the example above, but there are several issues to be solved: "membership card" how topointsThe contents of the "membership card", and how the customer uses the "loyalty card".

The Orthodox cookie distribution is implemented by extending the HTTP protocol,The server adds a special line of instructions to the HTTP response header to prompts the browser to follow the instructions to generate the appropriate cookie. However, purely client-side scripts such as JavaScript or VBScript can also generate cookies.  

cookies are used by the browser in accordance with aautomatically sent to the service in the backgroundDevice's. Browser Check all stored cookies, if a cookie declares a scope greater than or equal to the location of the resource to be requested, the cookie is appended to the HTTP request header of the requesting resource. sent to the server. McDonald's membership card can only be presented at the McDonald's store, if a branch also issued its own membership card, in addition to the store to show McDonald's membership card, but also to show this store's membership card.  
the contents of the cookie mainly include: name, value, expiration time, path and domain.
where a domain can specify a domain such as. google.com, which is equivalent to the head office signs, such as the company, can also specify a domain under a specific machine such as www.google.com or froogle.google.com, can be used to make the ratio of fluttering.
The path is the URL path that follows the domain name, such as/or/foo, and so on, can be used to do a certain float-soft counter.
The combination of the path and the domain constitutes the scope of the cookie.
If you do not set an expiration time, the cookie will not be in the lifetime of the browser session, as long as the browser window is closed. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated. If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and the cookies remain valid until the set expiration time expires.

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 have different ways of handling them. For IE, a window that is opened by pressing CTRL-N (or from the File menu) on an open window can be shared with the original window, while the other way of opening the IE process does not share the memory cookie of the opened window; for Mozilla Firefox0.8, all processes and tabs can share the same cookie. In general, a window opened with JavaScript's window.open will share the memory cookie with the original window. The browser's approach to cookie-only recognition of session cookies is often a major problem for Web application developers who use the sessions mechanism.

Here is an example of a goolge setting a cookie's response header
http/1.1 302 Found
location:http://www.google.com/intl/zh-cn/
Set-cookie:pref=id=0565f77e132de138:nw=1:tm=1098082649:lm=1098082649:s=kaeacfpo49ria_d8; Expires=Sun, 17- Jan-2038 19:14:07 GMT; path=/; Domain=.google.com
content-type:text/html
The browser automatically sends out cookies when accessing Goolge resources again

Understanding the session mechanism 
The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information.

when a program needs to create a session for a client's request, the server first checks to see if a session ID is included in the client's request-called the session ID. If itcontains a session The ID indicates that the session was previously created for this client, and the server retrieves the session using the session ID (if it is not retrieved, it may create a new one) if the client request does not include the session ID. Creates a session for this client and generates a session Id,session ID value associated with this session should be a string that is neither duplicated nor easily found to mimic the pattern, this session The ID will be returned to the client in this response to be saved. This session ID can be saved by using a cookie, so that the browser can automatically play the logo to the server during the interactive process. Generally the name of this cookie is similar to Seeesionid, and. For example, WebLogic for Web application generation cookie,jsessionid=byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!- 145788764, its name is Jsessionid.
Since cookies can be artificially banned, there must be other mechanisms that can still pass the session ID back to the server when the cookie is banned. Often used in a technique called URL rewriting , is to attach the session ID directly behind the URL path, there are two additional ways, one is as the URL path of additional information , the representation of http://...../xxx; Jsessionid=byok ... 99zwpbng!-145788764
The other is appended to the URL as a query string, in the form of Http://...../xxx?jsessionid=ByOK ... 99zwpbng!-145788764
these two ways for the user is no difference, but the server in the resolution of the way the process is different, the first way is also conducive to the session ID information and normal program parameters separated.
In order to maintain state throughout the interaction, the session ID must be included after each client may request a path.

Another technique is called a form-hidden field. Is that the server automatically modifies the form, adding a hidden field so that the session ID can be passed back to the server when the form is submitted. This technique is now less applied, and the very old IPlanet6 (the predecessor of the SunOne Application server) that the author has contacted has used this technique.
In fact, this technique can be replaced simply by applying URL rewriting to the action.

when we talk about the session mechanism, I often hear a misunderstanding that "as soon as you close the browser, the session disappears." In fact, you can imagine the membership card example, unless the customer actively to the store to sell cards, otherwise the store will not easily delete customer information. For the session is the same, unless the program notifies the server to delete a session, or the server will remain, the program is generally in the user to log off when sending an instruction to delete the session. However, the browser will never proactively notify the server before shutting down, so the server will not have the opportunity to know that the browser has been shut down, the reason for this illusion is that most of the session mechanism uses a conversation cookie to save the sessions ID, The session ID disappears when you close the browser, and you cannot find the original session when you connect to the server again. If the cookie set by the server is saved to the hard disk, or if a device is used to overwrite the HTTP request header sent by the browser, and the original session ID is sent to the server, the original session can still be found by opening the browser again.

It is precisely because closing the browser does not cause the session to be deleted, forcing the server to set an expiration time for seesion, when the client last time to use the session more than the expiration time, the server can assume that the client has stopped the activity, The session is deleted to save storage space.


Summary 
The session mechanism itself is not complex, but its implementation and configuration flexibility makes the specific situation complex and changeable. This also requires that we do not have a single experience or a particular browser, server experience as a universally applicable experience, but always need specific circumstances specific analysis.

How the session Works

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.