Cookie client cache. session.application

Source: Internet
Author: User
Tags response code send cookies subdomain

Cookie Client cache.

1. Introduction

As browsers become more capable of processing, more and more websites are starting to think about storing data in the "client", so they have to talk about local storage for a long time.

Benefits of local Storage:

One is to avoid retrieving data before the page blank, if you do not need the latest data can also reduce the number of requests to the server, thereby reducing the user waiting for data from the service side time.

The second is that the offline data can still be displayed when the network status is poor.

2. Local Storage

To open a Web page in Chrome, F12 into developer mode and click Application, we can see:

The above local stroage, Session Stroage, IndexedDB, and Cookies are some of the commonly used native storage.

3. Common Local Storage

1) Cookies

is an option that the client uses to store the data, which can be set on the client or server side. Cookies are sent along with any HTTP request.

Pros: Good compatibility

Disadvantages: One is to increase the network traffic, the second is the limited data capacity, up to the storage of up to 4kb of data, the browser is different, three is not safe.

2) UserData

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

Cons: Not part of the Web standard, only IE support.

3) Web Storage mechanism

Web Stroage, including: Session Stroage and Local stroage,

The former is strictly used to store data in a browser session because the data is deleted immediately after the browser is closed, and the latter is used to persist data across sessions.

Disadvantage: IE does not support session stroage, the low version of IE (IE6, 7) does not support local stroage, and the query language is not supported.

4) IndexedDB

The short name of the Indexed database API is a "database" for storing structured data in a browser. A structured data storage mechanism similar to SQL databases, instead of a long-discarded Web SQL database API.

Advantage: the ability to store large amounts of structured data on the client and use an index to efficiently retrieve the API.

Cons: Poor compatibility, not supported by most browsers.

4. Use of cookies

Cookie attribute of Document Object

A cookie is a small piece of textual information that accompanies a user request to be passed between a Web server and a browser. It is stored on the visitor's computer and is sent whenever the same computer requests a page through a browser.

First, it is a mechanism provided by the "browser",

It provides the cookie property of the Document object to JavaScript, which can be used to create and retrieve the value of the cookie, so we can access it through Document.cookie.

A cookie is a file that is stored on a user's hard drive, which usually corresponds to a domain name, which means that a cookie can span multiple pages under a domain name, but not across multiple domain names.

the fundamental use of cookies

A cookie stores information on a user's hard disk, so it can be used as a global variable, which is one of its greatest advantages. Its most fundamental use is that cookies can help a Web site keep information about visitors.

  Enumerate several small uses of cookies

1) Save user login information. This should be the most common. When you visit a login interface, such as Weibo, Baidu and some forums, there will generally be similar to the "Next automatic Login" option after the login, check the next time you do not need to repeat the verification. This allows the user's ID to be saved through a cookie.

2) Create a shopping cart. Shopping sites usually keep the selected items in a cookie, which enables synchronization of data between different pages (a cookie can be shared under the same domain name), and the cookie is uploaded to the background when the order is submitted.

3) Tracking user behavior. For example, Baidu Alliance will use cookies to record users ' preferences, and then recommend personalized promotional information to users, so when browsing other web pages are often found next to the small ads are their own recent Baidu search for things. This can be disabled, which is one of the drawbacks of cookies.

  How does a cookie work?

In the previous section we know that cookies are present on the user's hard drive, and each time a user accesses a site, the Web application can read the information contained in the cookie. When the user accesses the site again, the browser looks for the URL associated with the local hard drive Cookie . If the Cookie exists, the browser adds it to request header the Cookie field and sends it http请求 together to the site.

4. Cookie format and common attributes

String law: (1) Each cookie is in the form of a name/value pair, that is name=value , (2) the name and value must be URL encoded, (3) and between the two pairs cookie to 分号 和 空格  separate.

The line marked in red, a little conjecture, can also be known as a cookie-related value and attribute. Name, value, needless to say, is naturally the name and value of the cookie. Domian, Path, Expires/max-age,

The properties of the military cookie such as Size, Http, secure, and so on.

Let's add a few cookies manually, with the following code:

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

Together, these two options determine which pages a cookie can be shared with.

The red zone is the default, as in Example 1, domain and path are not set to the final display.

domainThe parameter is used to control which domain the cookie is valid for "which domain", which defaults to setting the cookie. This value can include a subdomain, or it may not contain it. As an example, the domain option can be " .google.com.hk " (without a subdomain, which means it is google.com.hk valid for all subdomains), or " www.google.com.hk " (including subdomains).

pathThe "path" to the specified domain that controls the sending of a cookie, and the default is "/", which means that all paths under the specified domain can be accessed. It is based on the domain name and specifies the path that can be accessed. For example, if the cookie is set to " domain=.google.com.hk; path=/webhp ", then only .google.com.hk/webhp any subdirectories under "and", /webhp such as " /webhp/aaa or" will send cookie information and "" will not be /webhp/bbb .google.com.hk sent, even if they are from the same domain.

Expries/max-age Failure Time

Expries and Max-age are used to determine the life cycle of a cookie, that is, when a cookie is deleted.

Expries represents the expiration time, which is exactly the "time period" in which "",max-age "is effective, in" seconds ".

max-age A positive value indicates that the cookie will expire after max-age seconds. If the "max-age=10800;" is set in example four, that is, the effective time is 3 hours, then the cookie will expire after three hours.

If max-age negative, the cookie expires at the end of the browser session, that is, the default value of Session,max-age is-1. If max-age 0, the cookie is deleted.

Secure

By default, no secure option is specified, that is, both HTTP requests and HTTPS requests will send cookies.

Is the security flag of a cookie and is the only part of a cookie that is not a key-value pair. Once specified, the cookie is sent to the server only if the connection is used SSL (such as HTTPS a request or other security protocol).

HttpOnly (that is, HTTP)

httponlyproperty is used to restrict client script access to cookies. Setting a cookie to httponly can mitigate the risk of XSS (cross site scripting attacks across the Scripting) attack.

Prevent cookies from being stolen to enhance the security of cookies. (due to the possibility of storing authentication information in a cookie, it can be easily disclosed in a cookie)

By default, HttpOnly is not specified, which can be accessed via JS.

5, how to use the above attributes to set a cookie?

Server-side settings

The server Set-Cookie creates a cookie by sending an HTTP header named as part of the Response Headers. As shown, each Set-cookie represents a cookie ( if multiple cookies are required to write multiple Set-cookie), and each attribute is also in the form of a name/value pair (except secure ), separated by a semicolon and a space between the attributes. The format is as follows:

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

Only cookie the name and value are required.

  Client settings

The client sets the same format as the one used in the cookie Set-Cookie header. As follows:

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

If you want to add multiple cookies, you can only repeat them document.cookie (as above). This may be written in peace when JS is not the same, the general repetition of the assignment will be covered,

For a cookie, however, the Document.cookie is repeatedly executed and "not overwritten", but "added" (for different names).

6. Disadvantages of cookies

Security: Because the cookie is passed in plaintext in HTTP, the data contained in it can be accessed by others and may be tampered with and embezzled.

Size limit: The cookie size is limited to around 4KB and is not suitable for large storage.

Increased traffic: Each request is automatically added to the request header, which virtually increases traffic. The larger the cookie information, the longer it takes to request the server.

Session Server cache.

One:

Website development, in order to save the user information we will use the session.

The session has the following characteristics:
(1) The data in session is saved on the server side;
(2) Any type of data can be saved in session;
(2) The session default life cycle is 20 minutes, you can manually set a longer or shorter time.

Our invocation in the ASPX page is generally only required to write:<%=session["key"]=value%>;

This is generally said when getting a session:string username=session["username", but we need to pay attention to two points when assigning values to an object.

1: Determine if NULL

2: Conversion of types

Example:

Use the Session object to transfer the user's login name, display the user's login name on another page//use the Session object to save the user's login name in the following code: Session.remove ("UserName"); session["UserName"] = txtName.Text; Response.Redirect ("a.aspx");

Redirect is used here to jump to the specified page, it is important to note: If our request is through the Ajax method, redirection is not working!

OK, so let's analyze the reason for Response.Redirect's jump:

->response.redirect is a local jump, does not serve the end of the jump, is to the browser to output a response code, the response code of 301 or 302, tell the browser to jump.

Two:

A: Using Session variables
The use of Session variables is another way to pass values between pages, in this case we have the value in the control in the session variable, and then use it in another page to achieve the purpose of passing values between different pages. However, it is important to note that storing too much data in the session variable consumes more server resources, should be cautious when using the session, and of course, we should also use some cleanup actions to remove unnecessary sessions to reduce the unnecessary consumption of resources.

Release method: Session.remove ();

Session.removeall ();

Session. Abandon ();

B:session the use of the passed array:

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 authenticate user login

if (txtName.Text = = "Mr" && txtpassword.text = = "Mrsoft") {session["UserName"] = TxtName.Text.Trim (); Response.Redirect ("a.aspx");}

The default expiration period for session objects is 20 minutes, and users can set them in Web. config.

When I use the session reminds me of the viewdata I used, I feel that both can play a role in the value of the transfer.

Weak types in MVC, mainly ViewData and TempData
In fact, it should be a dictionary for key-value correspondence, respectively, corresponding to Viewdatadictionary and tempdatadictionary.
ViewData can only be used in the current HTTP request and will not be able to take the data to the next HTTP request as a session.
The difference between TempData and ViewData is that he is temporary, such as replacing some viewstatus to save the last data for the client. His interior is preserved through the session. Automatically clears the session as long as it is taken once.

... Cond!

Application Global Application variables.

The Application object lifetime is as long as the Web application lifetime, starting with the Web application Web page being accessed, and the HttpApplication class object
Application is automatically created until no page is accessed and the Application object is automatically revoked. So the variables in the Application object also have
The same lifetime, and the variable can be accessed by all pages in the Web application. Therefore, you can establish some global public variables in the Application object, as stored in the
The values in the Application object can be read by all pages of the application, so the properties of the Application object are also suitable for passing information between Web pages of the application.
Application objects are mainly used for the following purposes:
L Store variables that record the number of people online or the total number of visitors to the site.
L Store Web site sharing the latest news for all Web pages to update.
L record the number or time that the same ad was clicked on a Web page.
L Store database data for use by all Web pages.
L Communication between different uses, such as multi-user chat room, multi-user games, etc.
This section first describes the use of the Application object, and then describes how to record the total number of visitors to the site.

11.4.1 Application Object Properties
Although the Application object does not have built-in properties, we can use the following syntax to set a user-defined property also called a collection: Application ("Property/collection name
called ") = value, for example, application (" MyVar ") =" Hello ". Use the following statement to extract the data: string s=
Application ("MyVar").

11.4.1 method
Application
The Application object has two methods, both of which are used to handle synchronization issues that multiple users write to the data stored in the. Because the values stored in the Application object
Can be read by all the Web pages of the application, so that when a user modifies this variable, no other user is allowed to modify it, both methods are to solve the problem.
L 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 the user does not explicitly call the Unlock method, the server will unlock the Application object after the. asp file ends or times out.
L Unlock Method
In contrast to the lock method, the Unlock method allows other clients to modify the properties of the Application object. The following example shows how a counter variable is used.
Application.Lock;
application["Counter"]= (Int32) application["Counter"]+1;
Application.UnLock;

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

Cookie client cache. session.application

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.