Cookie, Sesstion, and Application cache ., Cookiesesstion

Source: Internet
Author: User
Tags send cookies subdomain

Cookie, Sesstion, and Application cache ., Cookiesesstion

Cookie client cache.

1. Introduction

With the increasing processing capability of browsers, more and more websites are considering storing data on the "client", so they have to talk about local storage for a long time.

Benefits of Local Storage:

First, avoid blank pages before retrieving data. If you do not need the latest data, you can also reduce the number of requests sent to the server, thus reducing the user's waiting time to obtain data from the server.

Second, offline data can still be displayed when the network status is poor.

2. Local Storage

Open a Web page in chrome, F12 enters the developer mode, and click Application, we can see:

 

The preceding Local Stroage, Session Stroage, IndexedDB, and Cookies are common types of Local storage.

3. Common Local Storage

1) cookie

Is an option used by the client to store data. It can be set either on the client or on the server. The cookie will be sent along with any HTTP request.

Advantage: good compatibility

Disadvantages: first, the network traffic is increased, second, the data capacity is limited, and a maximum of 4 kb of data can be stored. The browsers are different, and third, they are insecure.

2) userData

Is a concept of persistent user data introduced by Microsoft through a custom behavior. User data allows up to KB of data per document, and up to 1 MB of data per domain name.

Disadvantage: it is not part of the web Standard and only supports ie.

3) web storage mechanism

Web Stroage, including Session Stroage and Local Stroage,

The former is used to store data in a browser session, because the data will be deleted immediately after the browser is closed; the latter is used to store data persistently across sessions.

Disadvantages: ie does not support Session Stroage. Earlier ie (ie6 and 7) does not support Local Stroage and does not support query languages.

4) IndexedDB

The Indexed Database api is short for storing structured data in a browser 」. Similar to the structured data storage mechanism of SQL databases, SQL Database APIs have been abandoned for a long time.

Advantage: it can store a large amount of structured data on the client and use an index-efficient retrieval api.

Disadvantage: poor compatibility, not supported by most browsers.

4. Usage of cookies

Cookie attribute of the document Object

Cookie is a short text message that is transmitted between the web server and the browser along with user requests. It is stored in the visitor's computer. This cookie is sent whenever a computer requests a page through a browser.

First, declare that it is a mechanism provided by the browser,

It provides the cookie attribute of the document Object to JavaScript. You can use JavaScript to create and retrieve the cookie value, so we can access it through document. cookie.

A cookie is a file stored on the user's hard disk. This file usually corresponds to a domain name. That is, a cookie can span multiple webpages under a domain name, but cannot be used across multiple domain names.

Basic usage of cookies

Cookie stores information on the user's hard disk, so it can be used as a global variable, which is one of its biggest advantages. Its most fundamental purpose is that cookies can help websites save information about visitors.

  List several small uses of cookies

1) Save the user logon information. This should be the most common one. When you access an interface that requires logon, such as Weibo, Baidu, and some forums, there will usually be an option similar to "next Automatic Logon" after logon. After you select this option, you do not need to verify it again next time. In this way, the user id can be saved through cookies.

2) create a shopping cart. Shopping websites usually store the selected items in cookies to synchronize data between different pages (the cookie can be shared under the same domain name ), at the same time, these cookies will be uploaded to the background when the order is submitted.

3) tracking user behavior. For example, Baidu Alliance records users' preferences through cookies and recommends personalized promotion information to users. Therefore, when Browsing other web pages, it often finds that the Small advertisements next to them are the items that Baidu has searched recently. This can be disabled, which is also one of the drawbacks of cookies.

  How does cookie work?

In the previous section, we know that the cookie exists on the user's hard disk. Every time a user accesses the site, the Web application can read the information contained in the Cookie. When the user visits the site again, the browser will findCookie. If the Cookie exists, the browser adds itrequest headerOfCookieField, andHttp RequestSent to the site together.

4. cookie format and common attributes

 

String rules: (1) Each cookie is in the form of a name/value pair, that isname=value, (2) names and values must both beURLEncoded, (3) and two pairscookieTakeSemicolon and Space.

The line marked in red can also be guessed as cookie-related values and attributes. The name and value are not required to be mentioned. They are the names and values of cookies. Domian, Path, Expires/max-age,

Size, Http, Secure, and other military cookie attributes.

First, manually add several cookies.,The Code is as follows:

document.cookie = "test1=myCookie1;"document.cookie = "test2=myCookie2; domain=.google.com.hk; path=/webhp"document.cookie = "test3=myCookie3; domain=.google.com.hk; expires=Sat, 04 Nov 2017 16:00:00 GMT; secure"document.cookie = "test4=myCookie4; domain=.google.com.hk; max-age=10800;"

Domain and path

These two options jointly determine which pages can share a cookie.

The highlighted red area is the default, as in Case 1, domain and path are not set to display.

domainThe parameter is used to control the domain in which the cookie is valid. By default, it is the domain in which the cookie is set. This value can contain or not contain a subdomain. For example, the Domain option can be".google.com.hk"(Does not contain a subdomain, indicating that it hasgoogle.com.hk), Or"www.google.com.hk"(Including subdomains ).

pathThe "path" of the specified domain used to control cookie sending. The default value is "/", indicating that all paths in the specified domain can be accessed. It specifies the accessible path based on the domain name. For example, if the cookie is set"domain=.google.com.hk; path=/webhp", Then only".google.com.hk/webhp"And"/webhp"Any subdirectory under"/webhp/aaa"Or"/webhp/bbb"Will send cookie information, while".google.com.hk"Will not be sent, even if they come from the same domain.

Expries/max-age expiration time

Expries and max-age are used to determine the cookie lifecycle, that is, when the cookie will be deleted.

Expries indicates the expiration time, accurate to "time", and max-age indicates the effective "time period", in seconds.

Ifmax-ageIf the value is positive, the cookie will expire after max-age seconds. If "max-age = 10800;" is set in example 4, that is, the cookie takes effect for three hours.

Ifmax-ageIf the value is negative, the cookie will expire after the browser session ends, that is, session. The default value of max-age is-1. Ifmax-ageIf the value is 0, the cookie is deleted.

Secure

The default value is null. If the secure option is not specified, both http requests and https requests send cookies.

It is the security identifier of a cookie and the only non-key-value pair in the cookie. After the cookie is specified, it is only usedSSLConnection (for exampleHTTPSRequests or other security protocol requests) will be sent to the server.

Httponly (http)

httponlyAttribute is used to restrict access to cookies by client scripts. Setting the cookie to httponly can reduce the risk of Cross Site Scripting (xss) attacks,

Prevent cookie Theft to enhance the security of the cookie. (Because the cookie may store authentication information, it is easy to leak it in the cookie)

By default, httponly is not specified, that is, it can be accessed through js.

5. How can I use the above attributes to set cookies?

Server Settings

The server sendsSet-CookieCreate a cookie as part of the Response Headers. As shown in, each Set-Cookie represents a cookie (If multiple cookies exist, you need to write multiple Set-cookies.), Each attribute is also in the form of a name/value pair (secure). Properties are separated by semicolons and spaces. The format is as follows:

; Domain = domain] [; path = path] [; secure]

OnlycookieIs required.

  Client settings

Client settingscookieFormat andSet-CookieThe format used in the header is the same. As follows:

; Domain = domain] [; path = path] [; secure]"

If you want to add multiple cookies, you can only execute them again.document.cookie(As shown above ). This may not be the same as the JavaScript code written in time. Generally, repeated values will be overwritten,

For cookies, the document. cookie is repeatedly executed and "not overwritten", but "added" (for "different names ).

6. disadvantages of cookies

Security: Because cookies are transmitted in plain text in http, the data contained in cookies can be accessed by others and may be tampered with or stolen.

Size Limit: the cookie size is limited to about 4 kb, which is not suitable for storing large volumes of data.

Increase Traffic: Each cookie Request is automatically added to the Request Header, which virtually increases the traffic. The larger the cookie information, the longer the request to the server.

 

SessionServer cache.

I:

In website development, session is used to save user information.

Session has the following features:
(1) The Session data is stored on the server;
(2) The Session can store any type of data;
(2) The default Session lifecycle is 20 minutes. You can manually set a longer or shorter time.

We generally only need to write the following code for calling on the aspx page:<% = Session ["key"] = value %>;

This is generally the case when the session is obtained:String username = session ["username"]But when assigning values to objects, we needNote:

1: judge whether it is null

2: type conversion

Example:

// Use the Session object to send the user's login name. On the other page, the user's login name is displayed // The code for saving the user login name using the Session object is as follows: Session. remove ("UserName"); Session ["UserName"] = txtName. text; Response. redirect (". aspx ");

Here, the redirection is used to jump to the specified page. Note that:If our request uses the Ajax method, redirection does not work!

Well, let's analyze the cause of Response. Redirect jump:

-> Response. Redirect is a local jump without a server jump. It outputs a Response code to the browser, which is 301 or 302, telling the browser to jump.

II:

A: Use Session variables.
Using the Session variable is another way to pass values between pages. In this example, we store the value in the control in the Session variable and then use it on another page, to transfer values between different pages. However, it should be noted that storing too much data in the Session variable will consume a lot of server resources, so you should be careful when using the session. Of course, we should also use some cleanup actions to remove unnecessary sessions to reduce unnecessary resource consumption.

Release Method: session. remove ();

Session. removeAll ();

Session. Abandon ();

B: usage of the array transmitted by session:

protected void Button1_Click(object sender, EventArgs e)    {        ArrayList sArr = new ArrayList();        sArr.Add("0");        sArr.Add("1");        sArr.Add("2");        sArr.Add("3");        sArr.Add("4");        sArr.Add("5");        Session["Array"] = sArr;        ArrayList sRarr = new ArrayList();        string ssMsg = "";        sRarr = (ArrayList)Session["Array"];        ssMsg = sRarr[3].ToString();        Response.Write("<script>window.alert('" + ssMsg + "')</script>");    }

 

C: Use Session to verify User Logon

if (txtName.Text == "mr" && txtPassword.Text == "mrsoft"){Session["UserName"] = txtName.Text.Trim();Response.Redirect("a.aspx");}

The default expiration time of a Session object is 20 minutes. You can also set it in Web. Config.

When I use session, I think of viewdata that I have used. I feel that both of them can play the role of passing values.

Weak type in MVC, mainly including ViewData and TempData
Actually, they should all be dictionaries used for key-value ing, corresponding to ViewDataDictionary and TempDataDictionary respectively.
ViewData can only be included in the current HTTP request, and does not bring data to the next HTTP request like session.
The difference between TempData and ViewData is that it is temporary. For example, it replaces some viewstatus to save the last data of the client. It is saved internally through session. The session is automatically cleared once it is used.

... To be continued!

The global Application variable of the Application.

The lifetime of the Application object is as long as that of the Web Application. The lifetime starts when the Web Application webpage is accessed.
The Application is automatically created until no webpage is accessed and the Application object is automatically revoked. Therefore, the variables in the Application object also have
The same lifetime, and variables can be accessed by all Web pages in the Web application. Therefore, you can create some global public variables in the Application object.
The value in the Application object can be read by all web pages of the Application program. Therefore, the attribute of the Application object is also suitable for transmitting information between web pages of the Application program.
Application objects are mainly used for the following purposes:
L storage records the number of online users or the total number of visits to the website.
L stores the latest information shared by the website for updates on all webpages.
L records the number or time of clicks on the same advertisement on a website page.
L store database data for all web pages.
L communication between different users, such as multi-user chat rooms and multi-user games
This section first introduces the usage of the Application object, and then describes how to record the total number of visitors to the website.

11.4.1 Application Object Attributes
Although the Application object does not have built-in attributes, we can use the following syntax to set user-defined attributes, also known as collections: Application ("attribute/Set Name
It is called ") = value, for example, Application (" MyVar ") =" Hello ". Use the following statement to retrieve data: string s =
Application ("MyVar ").

11.4.1 Method
Application
There are two methods for objects. They are used to synchronize data written by multiple users in the Application. Because the value stored in the Application Object
It can be read by all web pages of the application. Therefore, when a user modifies this variable, other users are not allowed to modify it. These two methods solve this problem.
L ock Method
The Lock method prevents other customers from modifying the variables stored in the Application object to ensure that only one customer can modify and access the Application at the same time.
Variable. If you do not explicitly call the Unlock method, the server will Unlock the Application object after the. asp file ends or times out.
L Unlock Method
Opposite to the Lock method, the Unlock method allows other users to modify the attributes of the Application object. The following example describes how to use a counter variable.
Application. Lock;
Application ["counter"] = (Int32) Application ["counter"] + 1;
Application. UnLock;

11.4.1 event
L Application_OnStart event
Events that occur when the first browser accesses the Web application webpage.
L Application_OnEnd event
Events generated when a Web application webpage is not accessed by a browser.
The process of Application_OnStart and Application_OnEnd events must be written in the global. asax file.

 

Related Article

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.