Talking about Session/cookie

Source: Internet
Author: User

Session and Cookie are common web tracking technologies. Cookies are stored on the client side, while the session is saved on the server, and they are used to track the user's session state, which is an extended technique of the HTTP protocol. The reason for this is that the session and cookie are introduced as a complement to the HTTP protocol to compensate for the stateless nature of the HTTP protocol, thus maintaining state information between the user and the server.

1. Cookie mechanism

1.1 The function of cookies

In a Web program, it is important to keep the state of the session. In theory, one session should be maintained for each user, and all requests for the same user should belong to the same session, and all requests from the other user should belong to another session to differentiate between different user actions. As an example of online shopping, any product purchased by a user should be placed in a user's shopping cart, and all items purchased by B users should be placed in the shopping cart of the B user, and they are not in the same session, so they cannot be confused with each other.

The Web application transmits data using the HTTP protocol. HTTP protocol is a stateless protocol, once the data exchange is complete, the link between the client and the server will be disconnected, exchange data again need to establish a new link, which means that the HTTP protocol can not maintain the state between the client and the service side, tracking user's session information. Also take online shopping as an example, when a user bought a commodity and placed in their own shopping cart, when a user re-purchase goods when the server has not been able to determine whether the purchase behavior is a user, that is, two operations do not have any association between each other, causing inconvenience to users, seriously affecting the user's experience. To be able to track the information of a particular user, a technology that can record the user's information is required, and a cookie is a widely used technology.

In short, a cookie is a way of maintaining user information in the client under the HTTP protocol, a small text file stored by the Web server on the user's side, used to record information about the user, such as ID, password, pages visited, time spent, personal settings, and so on. During the validity period of a cookie, if a user accesses a site that has previously been visited, the server can take action by reading the cookie, such as setting up a personalized Web page, re-logging in without having to re-enter the user name and password, and so on.

How the 1.2 cookie works

(1). When a user accesses a website for the first time, the client does not have a cookie available, and when the server receives the user's request, if the user is set to allow cookies, the server will set up a cookie by returning a portion of the information along with the requested page to the user.

(2). Once the user accesses the same website again, the browser will look for the available cookie on the user's computer and, if found, include the cookie in the header of the HTTP request sent, and the server checks the cookie to determine the user's information. If it is not found, the first time you browse the site, use the form (1) to create a cookie.

A cookie is delivered using the header information of an HTTP request in a Web page code, and every request from the browser can be accompanied by a cookie.

Expiration date of 1.3Cookie

The validity period refers to the time the cookie record is stored and can be adjusted by setting the expire field of the cookie. If the cookie does not set a timeout event, it is stored in the browser's memory, and the cookie that accompanies the browser is erased, but if the cookie is set to a lifetime, then it is stored in the customer's hard drive, so that the cookie is not lost if the browser is closed. If the time of the next browser launch is within the lifetime of the cookie, the cookie is still available.

1.4 Setting the properties of a cookie

The properties of the cookie include name, value, expire, path, domain,secure.

Where name represents the name of the cookie, value is the corresponding values, the Expire field sets the expiration time of the cookie, in seconds, and the path of the cookie that determines the page to which the cookie can be accessed. This cookie can be accessed generally in the same directory as the page where the cookie was created or in a subdirectory of the Create Cookie page. If you want the parent or the entire Web page to be able to use cookies, you need to set the path, such as path=/; domain domains can solve the problem of accessing cookies under the same domain name, by specifying the host name of the accessible cookie to set. For example, "www.baiu.com" and "mp3.baidu.com" common one associated domain name "baidu.com", if you want to let the "www.baidu.com" cookie can be "mp3.baidu.com" access, We need to use the domain property of the cookie, and we need to set the path to "/"; secure is used to determine whether the cookie is transmitted using a secure protocol (HTTPS,SSL, etc.).

2. Session mechanism

Functions of the 2.1 session

The function of the session is the same as the function of the cookie, except that it is located in a different location. Cookies are used to record the user's state information on the client, and the session is used to store the properties and configuration information required by the user session on the server side, so that when the user jumps between the Web pages of the application, the variables stored in the session object will not be lost. It is maintained throughout the user's session.

Working mechanism of 2.2 session

(1). When a user accesses a service station for the first time, the session is created automatically, generating a unique session ID, and if a cookie is allowed, the only sign will be returned to the user with the request of the server and saved in the cookie. of course, not to visit all the sites will generate corresponding session, only to access the JSP, Servelet and other web programs to create a corresponding session, and access to such as HTML, An image such as a static Web application does not create a session.

(2). (in PHP) first use the Session_Start () function, which loads the existing session variable from the session library in PHP, and registers the session variable with Session_register () when executing the scripting language; At the end of the script execution , the non-destroyed session variable is automatically saved in the session library under a local path for the next load to be used to free up memory for the rest of the user, without causing memory overflow.

Validity period of 2.3 session

The session saved on the server side, regardless of whether the client still needs the session, and the server can not determine when the client will need the session again, but if the session is not destroyed in time, it will soon cause the server's memory shortage. In order to be able to have enough memory for all subsequent users, the session was created with a declaration period set.

Destroying and destroying a session can only be done in one of two ways:

(1). Displays the call Session.invalidate () method.

(2). The session exceeds its life cycle. After the session is generated, the server will update the user's session as soon as the user continues to access it. Each time the user visits the site, regardless of whether read or write session, the server will consider the user's session activity once. If the user's session is created at 10:00 and its declaration period is set to 20 minutes, then the session is destroyed if the user is not active at 10:00-10:20, and the user will continue to 10:30 if the page is re-accessed at 10:10.

2.4 Session's Method name and description

void SetAttribute (String attribute,object value) Set Session property

String getattribute (string attribute) gets the session property

Enumeration Getattributenames () Gets the name of the attribute that exists in the session

void RemoveAttribute (string attribute) removing session properties

String getId () returns the ID of the session. The ID is automatically created by the server and is not duplicated.

Long GetCreationTime () returns the date the session was created.                                                                                                 The return type is long and is often converted to a date type, such as Date Createtime=new date (session). GetCreationTime ())

Long Getlastaccessedtime () returns the last active time of the session, which can also be converted to date.

int Getmaxinactiveinterval () returns the timeout event for the session, in seconds

void Setmaxinactiveinterval (int second) sets the maximum timeout period for the session

void Putvalue (string attribute, Object value) is not recommended and has been superseded by setattribute (string attr)

Object getValue (string attribute) is not recommended and has been superseded by getattribute (string attr)

Boolean isnew () returns whether the session was newly created

void Invaliddate () invalidates the session

Each of these functions may have different implementations in different languages than the session object. For example, PHP Session_destroy () is used to clear a session file, Session_unset () is used to clear the memory of the session record.

Although the session is transparent to the user, the session implementation requires some support from the client. The use of the session requires a cookie as a flag, the HTTP protocol is stateless, the session cannot determine whether the two requests are the same user according to the HTTP protocol. When a user requests a response from the server, the server sends a cookie named Jsessionid to the client, whose value is the ID of the session. The session is based on the cookie to determine whether the same user. The cookie is automatically generated by the server and is generally valid only in the current browser, and is not shared between the browser's windows and the browser is disabled. Therefore, when the server is accessed by two browser windows of the same computer, two different sessions are generated. Except for windows that are opened by links, scripts, and so on in the browser window (that is, windows that are opened without double-clicking the browser icon). A window that is opened by a link, script, and so on in a browser window shares the cookie of the parent window and therefore shares the same session. For example, a child window can access the session of a parent window by right-clicking in the shortcut menu that pops up to select Open in New window.

2.5 Session for Cookie dependency characteristics

If the client prohibits the use of cookies in the browser's settings, the scheme is replaced by a URL rewrite. The URL address rewrite is to rewrite the session ID information that was used in the URL address. The server gets the ID of the session based on the re-URL.

Summarize:

Sessions and cookies are often used in conjunction to play a powerful role. For example, the user is a member of a store, then the user has the store assigned to the user ID or hold the store's membership card. Users each time the purchase will show their own membership card or directly tell the clerk himself in the store ID, used to indicate their identity, this is the role of cookies, is to indicate the identity of the user "ID." But the user presented a membership card or the user said their own ID, then the store teller will be in their own system or record to find the user's information, store the user information system or record is the session, is used to check the user information of a mechanism.

Talking about Session/cookie

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.