Cookies and session

Source: Internet
Author: User
Tags server memory

Session tracking is a common technique used in Web programs to track a user's entire session . Common session tracking techniques are cookies and sessions. The cookie determines the user's identity by logging information on the client , and thesession determines the user's identity by logging information on the server side .

1.1 Cookie Mechanism

In the program, session tracking is a very important thing. Theoretically, all request actions for one user should belong to the same session , and all request actions for another user should belong to another session, and they should not be confused. For example, any item that user a buys in a supermarket should be placed in A's shopping cart, regardless of when user a buys it, it belongs to the same session and cannot be placed in User B or User C's shopping cart, which is not part of the same session.

The Web application transmits data using the HTTP protocol. The HTTP protocol is a stateless protocol. Once the data has been exchanged, the client-to-server connection is closed, and exchanging the data again requires establishing a new connection. This means that the server is unable to track the session from the connection . that is, user a purchases a product into the shopping cart, and when the product is re-purchased, the server is unable to determine whether the purchase is a session of user A or User B. To track this session, you must introduce a mechanism.

Cookies are such a mechanism. It can compensate for the lack of HTTP protocol stateless. Before the session, basically all websites use cookies to track conversations.

1.1.1 What is a cookie

Cookies mean "Cookie", which is a mechanism developed by the Netscape community, which is proposed by the group . Cookies are now standard and all major browsers such as IE, Netscape, Firefox, and opera support cookies.

Because HTTP is a stateless protocol, the server does not know the identity of the client from the network connection. What do we do? give the client a pass, one per person, who must bring their own pass for whoever accesses it. This allows the server to confirm the identity of the client from the pass. That's how cookies work .

A cookie is actually a small piece of text information. The client requests the server and, if the server needs to log the user state, uses response to issue a cookie to the client browser. The client browser will save the cookie. When the browser requests the site again, the browser submits the requested URL along with the cookie to the server. The server checks the cookie to identify the user state. The server can also modify the contents of the cookie as needed.



It's easy to see the cookies issued by a website. Enter Javascript:alert (document. cookie) in the browser address bar (requires a network to view).

Note: The cookie feature requires browser support.

If the browser does not support cookies (such as the browsers in most phones) or if the cookie is disabled, the cookie function will expire.

Different browsers use different ways to save cookies.

IE will be saved as a text file under "C:\Documents and Settings\ your user name \cookies" folder, and a text file holds a cookie.

1.1.2 Record number of user visits

In Java, the cookie is encapsulated into the Javax.servlet.http.Cookie class. Each cookie is an object of the cookie class. The server operates on the client cookie by manipulating the cookie class object. get all cookies submitted by the client(in cookie[] array) via Request.getcookie (), via Response.addcookie (Cookiecookie) Set a cookie to the client.

The cookie object saves the user state in the form of a Key-value property pair, a cookie object that holds a property pair, and a request or response uses multiple cookies at the same time. Because the cookie class is located under Package javax.servlet.http.*, it is not necessary to import the class in the JSP.

1.1.3 Unicode Encoding: Saving Chinese

Unlike English characters, Chinese is a Unicode character that accounts for 4 characters in memory, while English is an ASCII character, which accounts for only 2 bytes in memory . Unicode characters are encoded in a cookie when Unicode characters are used, or are garbled.


Hint: Saving Chinese in a cookie can only be encoded. UTF-8 encoding is generally used. It is not recommended to use Chinese encoding such as GBK, because browsers do not support it and JavaScript does not support GBK encoding.


1.1.5 BASE64 encoding: Saving binary images

Cookies can use not only ASCII characters and Unicode characters, but also binary data. For example, using a digital certificate in a cookie provides a degree of security. Encoding is also required when using binary data.

% Note: This program is only used to show that cookies can store binary content and is not practical. Because the browser carries a cookie every time the server requests it, the cookie content should not be too much, otherwise it will affect the speed. The contents of the cookie should be few but good.


1.1.6 setting all properties of a cookie

In addition to name and value, cookies have several other commonly used properties. Each property corresponds to a getter method with a setter method. All the properties of the cookie class are shown in Table 1.1.

Table 1.1 Cookie Common Properties

Property name

Description

String Name

The name of the cookie. Once a cookie is created, the name cannot be changed

Object value

The value of the cookie. If the value is a Unicode character, the character encoding is required. If the value is binary data, you need to use BASE64 encoding

int MaxAge

The time, in seconds, that the cookie expires. If positive, the cookie expires after maxage seconds. If it is a negative number, the cookie is a temporary cookie and the browser is deactivated and the browser does not save the cookie in any way. If 0, the cookie is deleted. The default is –1

Boolean secure

Whether the cookie is only transmitted using security protocols. Security protocols. The security protocol has HTTPS,SSL, and so on, before transmitting data on the network to encrypt the data first. Default is False

String Path

The path to use for the cookie. If set to "/sessionweb/", only programs with ContextPath "/sessionweb" can access the cookie. If set to "/", the cookie can be accessed by ContextPath under this domain name. Note that the last character must be "/"

String Domain

The domain name in which the cookie can be accessed. If set to ". Google.com", all domain names ending with "google.com" can access the cookie. Note the first character must be "."

String Comment

A description of the use of the cookie. This description is displayed when the browser displays cookie information

int version

The version number used by the cookie. 0 indicates compliance with the cookie specification of Netscape, 1 is the RFC 2109 specification followed by the consortium


1.1.7 JavaScript Action Cookie

Cookies are stored on the browser side, so the browser has a prerequisite for manipulating cookies. Browsers can manipulate cookies using scripting programs such as JavaScript or VBScript. Here is a JavaScript example that describes common cookie operations. For example, the following code will output all cookies on this page.

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

Because JavaScript is able to read and write cookies arbitrarily, some good people want to use JavaScript programs to spy on users ' cookies on other websites. In vain, however, the organization has long recognized the security implications and preparedness of JavaScript to read and write cookies, and the standard browser will prevent JavaScript from reading and writing any cookies that are not part of its own web site. In other words, a Web site's JavaScript program reads and writes the cookie for the B site without any results.


1.1.8 Case: Permanent Login

If the user is on their own home computer on the Internet, log in to remember his login information, the next visit does not need to log in again, direct access. The way to do this is to keep the login information such as account number, password, etc. in the cookie, and control the validity of the cookie, and then verify the login information in the cookie on the next visit.

There are several scenarios for saving login information. The most direct is to keep the user name and password in the cookie, the next visit to check the cookie user name and password, compared with the database. This is a more dangerous option and generally does not store important information such as passwords in Cookies .

Another option is to encrypt the password and save it to the cookie, which is decrypted on the next visit and compared to the database . This scheme is slightly safer. If you do not want to save the password, you can also save the time stamp of the login to the cookie and the database, only to verify the user name and logon timestamp.

another way to achieve this is to encrypt the account according to certain rules, and save it to the cookie together with the account number. The next time you visit, you only need to determine whether the encryption rules are correct . This example saves the account to a cookie named account, which is encrypted with the MD1 algorithm and stored in a cookie named SSID. Verify that the account and key in the cookie are encrypted with the same SSID as the cookie.

Tip: The most important part of this encryption mechanism is the algorithm and key. Because of the irreversibility of the MD1 algorithm, even if the user knows the account and the encrypted string, it is impossible to decrypt the key. Therefore, the mechanism is safe as long as the key and algorithm are kept.


1.2 Session mechanism

In addition to using the Cookie,web application, the session is often used to record client status. session is a server-side use of the mechanism to record client status , the use of more than a cookie is simpler, the corresponding increase the storage pressure of the server.

1.2.1 What is a session

The session is another mechanism for recording the state of a customer, but the cookie is stored in the client browser and the session is stored on the server. When the client browser accesses the server, the server logs the client information to the server in some way. This is the session. when the client browser accesses it again, it only needs to find the customer's status from that session.

If the cookie mechanism is to determine the customer's identity by checking the "pass" on the client, then the session mechanism verifies the customer's identity by checking the "customer schedule" on the server. Session is equivalent to a program on the server set up a customer profile, when customers visit only need to query the customer file table on it.

1.2.2 Implementing User Login

The class corresponding to the session is the Javax.servlet.http.HttpSession class. Each caller corresponds to a Session object, and all of the client's status information is stored in the session object. The session object is created the first time the client requests the server . The session is also a Key-value property pair that reads and writes client state information through the getattribute (Stringkey) and setattribute (String key,objectvalue) methods. The servlet obtains the client's session through the Request.getsession () method,

When multiple clients execute a program, the server saves sessions for multiple clients. There is no need to declare who gets the session when you get the session. The session mechanism determines that the current customer will only get their own session, and will not get to the other person's session. Each client's session is independent of each other and is not visible to each other .

Note :session usage is more convenient than cookies, but too many sessions are stored in server memory, which can cause stress to the server.


The life cycle of the 1.2.3 session

Session is saved on the server side. In order to obtain higher access speed, the server usually puts the session in memory. Each user will have a separate session. If the session content is too complex, a large number of clients accessing the server can cause memory overflow. Therefore, the information in the session should be as concise as possible.

session is created automatically when the user accesses the server for the first time . It is important to note that only access to the JSP, servlet, and other programs will create a session, access only static resources such as HTML, image, and do not create session. If the session has not been generated, you can also use Request.getsession (true) to force the session to be generated.

S Once the ession is generated, the server updates the last access time of the session as long as the user continues to access, and maintains the session . each time a user accesses a server, the server considers the user's session "active" once, regardless of whether the session is read or written.


Validity period of 1.2.4 session

As more and more users access the server, the session will be more and more. to prevent memory overflow, the server removes the session from memory that has not been active for a long period of time. This is the time-out period of the session. If you have exceeded the time-out period and have not accessed the server, the session will automatically expire.

The timeout period for the session is Maxinactiveinterval property, which can be obtained through the corresponding Getmaxinactiveinterval () and modified by Setmaxinactiveinterval (Longinterval).

The timeout period of the session can also be modified in Web. Xml. In addition, by invoking the invalidate () method of the session, the session can be invalidated.


Common methods of 1.2.5 session

The session includes a variety of methods that are much more convenient to use than cookies. The common methods of the session are shown in table 1.2.

Table 1.2 Common methods of HttpSession

Method name

Description

void SetAttribute (String attribute, Object value)

Sets the session property. The value parameter can be any Java Object. Typically a Java Bean. Value information should not be too large

String getattribute (String attribute)

Return to session Properties

Enumeration Getattributenames ()

Returns the name of a property that exists in the session

void RemoveAttribute (String attribute)

Remove 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, for example: Date Createtime = new Date (Session.get creationtime ())

Long Getlastaccessedtime ()

Returns the last active time of the session. return type is long

int Getmaxinactiveinterval ()

Returns the time-out period for the session. Unit is seconds. There is no access at this time, the server considers the session to be invalid

void Setmaxinactiveinterval (int second)

Sets the time-out period for the session. Unit is seconds

void Putvalue (String attribute, Object value)

The deprecated method. has been replaced by setattribute (String attribute, Object Value)

Object getValue (String attribute)

Methods that are not recommended. has been replaced by getattribute (String attr)

Boolean isnew ()

Returns whether the session is a newly created

void Invalidate ()

Invalidate the session

The default time-out for the session in Tomcat is 20 minutes. The time-out is modified by setmaxinactiveinterval (int seconds). You can modify Web. XML to change the session's default timeout time. For example, modify to 60 minutes:

<session-config>

<session-timeout>60</session-timeout> <!--units: minutes--

</session-config>


Note The:<session-timeout> parameter is in minutes, and setmaxinactiveinterval (int s) is the second unit.


1.2.6 session requirements for the browser

Although the session is saved on the server and is transparent to the client, it still needs the support of the client browser for its normal operation. This is because the session needs to use a cookie as the identification mark. The HTTP protocol is stateless, and the session cannot determine whether it is the same client based on an HTTP connection, so the server sends a cookie named Jsessionid to the client browser. Its value is the ID of the session (that is, the return value of Httpsession.getid ()). The session is based on the cookie to identify whether it is the same user.

The cookie is automatically generated by the server, and its MaxAge property is generally –1, which means that only the current browser is valid, and the browser windows are not shared, and the browser is disabled.

Therefore, when the server is accessed by two browser windows of the same machine, two different sessions are generated. However, new windows that are opened by links, scripts, and so on in the browser window (that is, not by double-clicking on Windows that are open by desktop browser icons). Such sub-Windows share a parent window's cookie, so a session is shared.


Note: The newly opened browser window will generate a new session, except for the child window. The child window will share the session of the parent window. For example, when you right-click on a link and select Open in New window in the popup shortcut menu, the child window can access the session of the parent window.

several ways to request the session ID to be saved
A. You can save the session ID by using a cookie so that the browser can automatically send the tag to the server in the interactive process.
B. Since cookies can be artificially banned, there must be other mechanisms to pass the session ID back to the server when the cookie is banned, a technique often called URL rewriting, which appends the session ID to the URL path, with two additional ways, One is additional information as a URL path, and the other is appended to the URL as a query string. The network always maintains state throughout the interaction and must include the session ID after each client may request a path. If the client cookie is disabled, the server canautomatically by overriding the URLto save the session value, and the process is transparent to the programmer. (except IE6.0)
C. 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.

What are the drawbacks of URL rewriting
use URL overrides for all URLs, including hyperlinks, action for form, and redirected URLs. Each URL that references your site, and the URLs that are returned to the user (even through indirect means, such as the Location field in server redirection), add additional information.

This means that you cannot have any static HTML pages on your site (at least static pages cannot have any links to site dynamic pages). Therefore, each page must be dynamically generated using a servlet or JSP. Even if all the pages are generated dynamically, if the user leaves the session and comes back again via a bookmark or link, the session information is lost because the stored link contains the wrong identity information-the session ID after the URL has expired.
What are the drawbacks of using hidden form fields
You can use this method only if each page is dynamically generated with a form submission. Click the General <a HREF: > Hypertext links do not generate form submissions, so hidden form fields cannot support normal session tracking, only for a specific set of operations, such as the checkout process for an online store.
 
Source: <cookie/session mechanism-look at the word-blog channel-csdn.net> http://www.blogjava.net/cheneyfree/archive/2007/05/26/120168.html


From for notes (Wiz)

Cookie and session (turn)

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.