Cookie and Session Introduction, CookieSession Introduction

Source: Internet
Author: User

Cookie and Session Introduction, CookieSession Introduction
Cookie and SessionThis chapter focuses on:

This chapter focuses on the concepts of cookies and sessions that are frequently used in Web development, their usage methods and application scenarios, as well as their advantages and limitations. A deep understanding and understanding of their usage can help us develop correct and available products.

 

 

Why do we need cookies and sessions:

Before starting the introduction of this provision, we need to ask ourselves a question: why do we need cookies and sessions? What problems can they help us solve?

Let's first understand what the HTTP protocol we often use: HTTP is an application protocol that belongs to the application layer and has the following five features:

  • Support clients <-> server services
  • Simple and fast
  • Flexible
  • No connection
  • Stateless

How do I understand the stateless features of HTTP? The popular phrase is "if life is just as first sight ". The HTTP protocol does not have the ability to process transaction requests, and there is no context relationship between requests for the same URL. Each HTTP request you send is independent, its execution and response results will not be affected by the previous HTTP requests. Of course, it will not affect subsequent HTTP requests and responses,The server processing the HTTP request does not save the client status..

We can imagine what kind of experience we would experience when visiting a network site without any special processing or improvement based on these features? Take online shopping for example. When we access an electronic mall, we are prompted to enter the user name and password. We enter the required information to log in successfully. A wide array of products are displayed in front of us, I have taken a look at the latest electronic product, and I plan to go in and take a look at the details. However, we are surprised by the next situation, because the server does not have our login status, why did my website Ask me to re-enter the user name and password? This would be a terrible user experience.

Obviously, this stateless feature of HTTP severely hinders our interaction with the server, so the two technologies used to maintain the HTTP connection status are generated by the application: Cookie and Session, this is also the focus of this chapter.

 

 

Cookie:What is a Cookie?

Looking at Wikipedia and Baidu encyclopedia, we can easily find that Cookie is a way in which servers or scripts are used to maintain customer workstation information under HTTP. It is a small text file stored on the user's browser (client) by the Web server. It can be used to record user activity or State-related information. Cookie was first developed and implemented by NetScape by W3C and has become a standard. Mainstream browsers support the Cookie mechanism.

The Cookie working mechanism can be found in the figure below:

As mentioned above, cookies are stored on client computers. Different browsers may have different storage paths. The following lists the storage locations of several common mainstream browsers:

  • IE storage location: C: \ Users \ {$ UserName} \ AppData \ Roaming \ Microsoft \ Windows \ Cookies \ xxx.txt
  • FireFox storage location: C: \ Users \ {$ UserName} \ AppData \ Roaming \ Mozilla \ Firefox \ Profiles \ {$ xxx. default} \ cookies. sqlite
  • Chrome storage location: C: \ Users \ {$ UserName} \ AppData \ Local \ Google \ Chrome \ User Data \ Default \ Cookies

Note: in IE browserSitesCookieSave separatelyIs a txt plain text file, while Firefox and ChromeAll cookies are stored in one file.The file format is SQLite3 database format.

 

Cookie attributes:

Common attributes of cookies can be found in the following table:

 

Server Side operation of Cookie:

To create a new Cookie, we can use the following code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Cookie myCookie = new Cookie("username", "WebOpenShare");myCookie.setMaxAge(300);myCookie.setDomain("www.webopenshare.com");myCookie.setPath("/");myCookie.setSecure(false);response.addCookie(myCookie);}

Run the code above to get a "username" with the corresponding value "WepOpenShare ". (If you are running a local Tomcat server, remember to modify the hosts file on your computer)

 

The Cookie object does not provide a method to directly modify its attributes. to modify the value of the original Cookie, we can only create a Cookie with the same name and add it to the response to overwrite the setting of the original Cookie, as follows:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// ...Cookie myModifiedCookie = new Cookie("username", "MyWebOpenShare");myModifiedCookie.setMaxAge(600);myModifiedCookie.setDomain("www.webopenshare.com");myModifiedCookie.setPath("/");myModifiedCookie.setSecure(false);response.addCookie(myModifiedCookie);}

Similarly, the Cookie object does not provide the Operation Method to directly delete a Cookie. to delete a Cookie, we can only create a new Cookie with the same name as maxAge 0, add it to response to delete the original Cookie, as shown in the following code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// ...Cookie deleted = new Cookie("username", "MyWebOpenShare");deleted.setMaxAge(0);deleted.setDomain("www.webopenshare.com");deleted.setPath("/");deleted.setSecure(false);response.addCookie(deleted);}

Note: When modifying or deleting a Cookie, we need to create a Cookie with the same name to overwrite it. For this Cookie with the same name, except that its value and maxAge attributes can be different, all other attributes must be consistent with the Cookie to be modified. Otherwise, the Operation will fail.

 

Client Side operation of Cookie:

We know that cookies are stored on the client. Can we use some scripting languages, such as JavaScript, to operate cookies in the browser? If so, can we perform read, write, modify, or even delete cookies just like operating cookies on the Server Side?

It is certain that we can use scripts to operate on cookies in the browser. However, for security reasons, the operations allowed by the scripts are very limited, and only the cookies under the current domain name can be read, you cannot modify or delete a Cookie. Through the following code, we can read the Cookies in the current Domain.

<script>document.write(document.cookie);</script>

 

What values should the Cookie store:

In the previous introduction, we mentioned that cookies are stored on client files. If the client is infiltrated, these Cookie files may be stolen. On the other hand, we all know that, HTTP uses plaintext transmission. If someone listens to or intercepts our requests, all the information we send to the server through cookies will be exposed to intruders. Therefore, the values stored in cookies should avoid personal sensitive information as much as possible. If you want to store sensitive key information, you must encrypt it before storing it.

 

 

Session:What is a Session?

Session is another solution for users to maintain the HTTP connection status. Unlike cookies, sessions are stored in the server memory, and the server uses a Hashtable) to store Session object information.

The Session is stored on the server, so it consumes server resources. Therefore, we should not store too many complicated and heavy objects and information in the Session. In the case of high concurrency, this will easily cause the server memory overflow to cause program exceptions or eventually downtime.

Session mechanism:

For more information about the Session mechanism, see:

 

When will a Session be created?

When will a Session be created? Is a Session created when we access the server? The answer is no. The server will create a Session object only when Session is called in the program. For example, in Servlet, when we call the request. getSession () method, the server creates a Session object. However, careful friends may find that when I access a JSP page, Session objects will also be generated, at this time, I did not explicitly use any request in Servlet or JSP. getSession () method. Here I particularly emphasize the explicit term. In fact, when we access JSP, JSP will add such code by default when compiled into Servlet: HttpSession session = request. getSession (), which is why we can use the session directly on the JSP page without doing anything. getAttribute () or other operations.

 

When will a Session be destroyed?

Previously, I talked about how to create a Session. Next, let's see when the Session will be destroyed? Of course, disabling the server ensures that all sessions are destroyed. Close the browser? Many people have a misunderstanding that as long as I close my browser, the Session will be destroyed. In fact, this understanding is not comprehensive. We know that the Session is created and maintained by the server, so the destruction must be completed by the server. Simply closing the browser does not trigger the action of destroying the memory, if we re-open the browser and send the previous Session ID to the server, we can retrieve the previous Session. This effect can be achieved only when a server request is triggered while the browser is closed and the server is told to destroy the memory.

It is precisely because the browser cannot be closed and the memory cannot be destroyed. For security reasons, we need to set a validity period for the Session. When an access request exceeds the validity period of the previous request, the previous Session will be destroyed and become invalid.

 

When a Cookie is disabled?

By default, the Cookie of the browser is required to work with the Session mechanism. After the server creates a new Session, it sends a Session ID to the browser, which is usually returned to the client in the form of a Cookie. In the following request, the client automatically carries the Session ID parameter in the request. The server directly searches the server for the previous Session object returned Based on the passed Session ID. But what if the client disables cookies?

Because cookies can be artificially disabled, there must be other mechanisms so that Session IDs can still be passed back to the server when cookies are disabled. A frequently used technology called URL rewriting is to directly append the Session ID to the end of the URL path. There are two additional methods, one is as the additional information of the URL path, the format isHttp: // $ {domain }:$ {port}/$ {uri}; SESSIONID = xxxxxxxxxxxThe other is appended to the URL as a query string, in the formHttp: // $ {domain }:$ {port}/$ {uri }? SESSIONID = xxxxxxxxxxx.

 

Common Session methods:

The common methods of Session are summarized as follows:

 

Throw an intro:

What about sharing data among different sessions? Please follow us and we will reveal your secrets in subsequent chapters.

 

I want to subscribe to sponsors and encourage the author to write better articles:

 

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.