Javaweb (ii) session Management the cookie and session

Source: Internet
Author: User
Tags session id sessions set time

Objective

The front spent a few blog introduction of the servlet, speaking very detailed. This article introduces you to cookies and session.

I. Session Overview 1.1, what is a session?

A session can be simply understood as: A user opens a browser, clicks multiple hyperlinks, accesses multiple Web resources on the server, and then closes the browser, the entire process is called a session.

A session refers to: Just like a phone call, A to B call, after the session started, until the end of the call, the session is over , and the browser access to the server, just like a phone call, browser A to the server to send a request, access to the Web program, the session has been connected,

Regardless of how many requests the browser sends (which is equivalent to talking on the phone), it is considered a session until the browser closes and the session ends. Note that a browser is the equivalent of a phone, if you use Firefox browser, access to the server, is a session,

then open Google Browser, access the server, this is another session, although it is on the same computer, the same user in the access, however, this is two times different sessions .

1.2. Session mechanism

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

Know what is the session, think of a problem, a browser to access a server can establish a session, if the other computer, all the same time to access the server, will create a lot of sessions, take some shopping sites, we visit a shopping site server, the session was created,

Then click on the product, to the interest of the product first added to the shopping cart, waiting for the bill together, this seems to be a very common operation, but think about it, if there are many other computers on the browser also access to the server of the shopping site, and we do similar operations? How the server remembers the user,

How do you know that any item purchased by user A should be placed in a shopping cart, whether it is purchased by user A or not in the shopping cart of User B or User C? So there is the cookie and the session of the two techniques, thecookie and session used to track the user's entire session .

Issues to be resolved by the session:

Each user in the process of using the browser and the server session, will inevitably produce some data, the program to find a way to save the data for each user .
For example, when a user clicks a hyperlink to buy a product through a servlet, the program should try to save the product that the user buys, so that when the user points out the servlet, the checkout servlet can get the product that the user buys to checkout the user.

Ii. Cookies and Session Overview 2.1, cookies

A cookie is a client-side technology in which a program writes each user's data to a user's browser in the form of a cookie. when users use a browser to access Web resources on the server, they take their own data. In this way, the Web resource handles the user's own data .

Because cookies are saved and carried by the client browser, they are called client technology : the API describes

    

2.2. Session

Session is a server-side technology , using this technology , the server at run time for each user's browser to create a unique HttpSession object, because the session for the user browser exclusive, So when a user accesses a server's Web resource,

can put their own data in the session , when the user to access other Web resources on the server, the other Web resources from the user's own session to remove data for the user Service .

2.3, the difference between the cookie and the session and contact

If a coffee shop has 5 cups of coffee free of charge for a cup of coffee, but a one-time consumption of 5 cups of coffee is negligible, then there is a way to record a customer's consumption. Imagine the fact that there are several options below:

1) The shop staff is very powerful, can remember each customer's consumption quantity, as soon as the customer enters the coffee shop, the clerk knows how to treat. This approach is the protocol itself that supports the state. But the HTTP protocol itself is stateless .

2) Send the customer a card, which records the amount of consumption, generally there is a valid period. If the customer presents this card each time it is consumed, the consumption will be linked to the previous or subsequent consumption.

This practice is to keep the state on the client. That is, cookies. The customer is equivalent to the browser, how the cookie works, the following will be explained in detail

3) to send the customer a membership card, in addition to the card number of what information is not recorded, each time the consumer, if the customer presents the card, then the shop clerk in the store records found this card number corresponding record add some consumer information. This is done by keeping the state on the server side .

Since the HTTP protocol is stateless and does not want to be stateful due to various considerations , the next two scenarios become a realistic choice. In particular , the cookie mechanism uses a scheme that maintains state on the client, while the session mechanism uses a scenario that maintains state on the server side .

We also see that the session mechanism may need to use a cookie mechanism to save the identity, but in fact it has other options because the server-side hold-state scheme also needs to preserve an identity on the client side.

Third, cookies

The above describes why cookies are used, and some of the characteristics of cookies, such as those stored on the client, used to record the identity of the user, and now look at how cookies are used.

By the above membership card example, the use of the second solution, which also need to solve the problem is: how to distribute the membership card, membership card content, how to use the membership card, membership card valid date, the use of membership card

1) How to distribute the contents of the membership card and membership card: that is, how the cookie was created? How do I send it to the client after creation?

Created by the server, it is equivalent to the coffee shop to create the membership card, in the creation of the membership card at the same time, will be the content of the membership card is also set

New  Cookies (Key,value); // Store content in key-value pairs,  Response.addcookie (cookie);  // send back to browser side   

Note: Once a cookie is created, you cannot add another key-value pair to it, but you can modify the contents of it.

Cookie.setvalue (); // Modify the value corresponding to the key

2) How does the customer use the membership card, how the cookie works on the client, and how does it work?

Figure One:

      

Figure II:

      

This process is equivalent to the coffee shop to create a good membership card, and has set up the content of the customer hand, the next time customers come over, take the membership card, you know you are a member, and then the coffee shop will get your membership card to operate it.

3) What is the valid date of the membership card? That is, a cookie also has a valid date.

This can be set freely, the default is to close the browser, the cookie is useless.

Cookie.setmaxage (expiry); // sets the time the cookie is saved by the browser.  Expiry: unit seconds, default is -1, expiry=-1: After the browser is closed, that is, after the end of the session, the cookie expires, there is no 。 expiry>0: After the browser is closed, the cookie does not expire and still exists. The cookie is saved to the hard drive until the set time expires and is automatically deleted by the browser , expiry=0: Delete the cookie. Regardless of the previous expiry=-1 or expiry>0, when set expiry=0 o'clock, the cookie will be deleted by the browser

4) How to use the membership card?

For example: Starbucks has a branch in Beijing, there is also a branch in Shanghai, we just in Beijing, Starbucks processing membership card, then when we go to Shanghai, we can not use the membership card to discount.

As with cookies, you can set the server-side access path to the cookie and not all servlets in the server-side Web project can access thecookie.

Cookie default path: the currently accessed servlet parent path .

Example: Http://localhost:8080/test01/a/b/c/SendCookieServlet

Default path:/test01/a/b/c that is, all Servlets under the default path are able to obtain a cookie,/test01/a/b/c/myservlet this myservlet to get a cookie.

Modifying access paths for cookies

     SetPath ("/");//Under this server, any item, any location can obtain a cookie.

Purpose: ensure that all Web projects under Tomcat can share the same cookie

For example: Tieba, Wenku, beike multiple projects share data. For example, user name.

SetPath ("/test01/"); Cookies can be obtained from any location under the TEST01 project.

Iv. detailed workflow of Cookie4.1 and cookies

1) servlet creates a cookie, saves a small amount of data, and sends a browser.
2) The browser obtains the cookie data sent by the server, which will be automatically saved to the browser side.
3) on the next visit, the browser will automatically carry cookie data to the server.

4.2. Cookie operation

1) Create Cookie:new Cookie (name,value)
2) Send cookie to Browser: Httpservletresponse.addcookie (cookie)
3) servlet receives all cookies sent by cookie:HttpServletRequest.getCookies () browser

4.3. Cookie Features

1) Each cookie file size:4kb , if more than 4KB browser does not recognize
2) a Web site (Web project): Send a
3) Total size of a browser:
4)Cookies are unsafe and may disclose user information. Browser support disables cookie operation .
5) Default life cycle: like a browser session, cookies are destroyed when the browser is closed . ---temporary cookies

4.4. Cookie API
GetName () Gets the name, the key GetValue () in the cookie gets the value, and the value SetValue (java.lang.String newvalue) setting in the cookie is used to modify the value corresponding to key  Value. Setmaxage (intexpiry) Set valid time "" SetPath (java.lang.String URI) set path "" "SetDomain (java.lang.String pattern) set domain name, generally invalid, have browser auto set, s Etdomain (". zyh.com") www.zyh.com/bbs.zyh.com can access a.b.zyh.com cannot access the role: Set the scope of the cookie, domain name+The path together constitutes the scope of the cookie, the SetPath that are set individually is useful because the domain Name property is automatically set by the browser, but we must know if the ishttponly () with this property for the domain name setting is only used by the HTTP protocol.  Only servlets are obtained through getcookies () and JavaScript is not available. Setcomment (java.lang.String Purpose) (learn)//The information describing the cookie (which describes the function), which the browser can see when it displays the cookie informationsetsecure (Boolean flag) (understanding) whether the secure transport protocol is used.  When True, the cookie is sent to the server side only if it is an HTTPS request connection, and HTTP is not, but the service can still be sent to the browser side. Setversion (intV) (understanding) parameter is 0 (traditional Netscape Cookie Specification compilation) or 1 (RFC 2109 specification compilation). This is useless, not very understanding

Note: Cookies cannot be sent in Chinese, and special processing is required if you want to send Chinese.

The JDK provides the tools to encode:

Urlencoder: Encoding

Urldecoder: Decoding

 //  send cookie   cookie Cookie  = new  Cookie (urlencoder.encode ( "  haha  " ), Urlencoder.encode ( Span style= "color: #800000;" > "  hehe  "   //  get cookie Chinese content    Urldecoder.decoder (Request.getcookie (). GetName);        //  get key   //  get value  
4.5. Cookie Application

1) Remember user name

Log in, the server side to obtain the user name, and then create a cookie, the user name into a cookie, sent back to the browser side, and then the next time the browser visits the login page, the first to get a cookie, the information in the cookie is taken out,

See if the user name is saved, if it is saved, then use it directly, if not, then write the user name yourself.

2) historical records

For example, the shopping site, there will be our browsing records, the implementation of the principle is also a cookie technology, each browse a product, it will be stored in a cookie, to the need to display browsing records, only want to take out the cookie to traverse.

V. Session

In the above introduction we know:

In web development, the server can create a session object for each user browser (Session object), note that a browser exclusively has a Session object (by default).

Therefore, when the user data needs to be saved, the server program can write the user data to the user's browser exclusive session , when users use the browser to access other programs, other programs can remove the user's data from the user's session, to serve the user .

Similarly, the membership card of the third method, issued to the customer a membership card, in addition to the card number of what information is not recorded, each time the consumer, if the customer presents the card, the clerk in the store in the Notepad to find the card number corresponding record add some consumer information.

This is done by keeping the state on the server side.  This is the use of the session, on the server side to maintain state, save some user information.

Function: Server for sharing data technology

      

5.1. Session principle Analysis

Let's describe it in two graphs: Although the code is the same, the different browsers get their own data

        

Schematic analysis diagram: How the server implements a session for a user browser service

      

First, when the browser requests the server to access the Web site, the program needs to create a session for the client's request, the server first checks whether the client request already contains a session ID , called SessionID,

If a SessionID is already included, it indicates that the session was previously created for this client, and the server will follow SessionID to retrieve the session, if the client request does not include the session ID. The server creates a session for this client and

To generate a session ID associated with this session, the value of SessionID should be a string that is neither duplicated nor easily found to mimic the pattern. SessionID will return to the client in this response to save, the way to save this sessionid can be a cookie,

In the process of interaction, the browser can automatically follow the rules to send this logo back to the server, the server according to this sessionid can find the corresponding session, and back to the beginning of the text.

5.2. Get session
Request.getsession (); // if no new, equivalent getsession (true) will be created;

Some people do not understand why the request to get the session, it can be understood that when the session is required to detect whether there is a session identifier, so need to use request to obtain

Request.getsession (Boolean); // true: No will be created, false: null will not be returned
5.3. Session Property operation
Xxxattribute (...)  Used to store some information before sharing information Setattrubute (Key,value); GetAttribute (key);
5.4. Session Life cycle

Often heard a misunderstanding "as long as the browser is closed, the session disappears." In fact, you can imagine the membership card example, unless the customer actively to the store to sell cards, otherwise the store will not easily delete customer information. It is the same for the session, unless the program notifies the server to delete a session,

Otherwise the server will always be retained, the program is usually when the user log off to send a command to delete the session. However, the browser will never proactively notify the server before shutting it off, so the server will never have the chance to know that the browser has been shut down .

The session ID is used by most of the sessions, and it is lost when the browser is closed, and the original session cannot be found when connecting to the server again. If the cookie set by the server is saved to your hard disk, or if you use some means to overwrite the HTTP request header sent by the browser,

Send the original session ID to the server, then open the browser again can still find the original session.

Just because the browser is closed does not cause the session to be deleted, forcing the server to set an expiration time for seesion, typically 30 minutes , when the client's last time to use the session exceeds the expiration time, The server can assume that the client has stopped activity before deleting the session to save storage space.

We can also control the session's effective time by ourselves:

Session.invalidate () Sets the effective time, in seconds, for the session object to be destroyed Setmaxinactiveinterval (int interval)

To configure the session's effective time in Web. xml:

<session-config> <session-timeout></session-timeout>    units: minutes <sessi On-config>

So, after a long discussion, the session's life cycle is:

Created: First call to GetSession ()

Destroyed:

1) Timeout, default 30 minutes

2) Execute api:session.invalidate () set the Session object destruction, Setmaxinactiveinterval (int interval) time, units: seconds

3) The server is not properly shut down

Kill yourself and shut down the JVM right away.

If you shut down normally, thesession will be persisted (written to the file, because the session default timeout is 30 minutes, after the normal shutdown, will persist the session, and so on after 30 minutes, will be deleted )

Location: D:\java\tomcat\apache-tomcat-7.0.53\work\Catalina\localhost\test01\SESSIONS.ser

5.5. URL rewriting of Session ID

When the browser disables the cookie, the cookie-based session will not work and a new session will be created each time the request.getsession () is used. The purpose of the session is not to share data, but we know the principle, only need to pass the session ID to the server session can work properly.

Workaround: Pass the session ID to the server via URL: URL rewrite

1) Manual mode: url;jsessionid= ....

2) API mode:

Encodeurl (java.lang.String URL) for all URL rewriting

     Encoderedirecturl (java.lang.String URL) for redirection URL rewriting

These two usages are basically the same, except for special cases where the link to be accessed may be redirect to other Servlets , so that the ID information of the session you bring with the above method cannot be transmitted to other servlets at the same time. This is the time to use the Encoderedirecturl () method.

If the browser disables COOKE,API will automatically append the session ID, if not disabled, the API will not make any modifications.

Note: If the browser disables cookies,all URLs for the Web project need to be rewritten. Otherwise the session will not work properly .

When the cookie is disabled:

    

Vi. summary of Cookies and session

The core of the cookie and session are described in detail above:

1) Know what is a cookie and session

A cookie is a technique for recording user information on a client, because the HTTP protocol is stateless and a cookie is created to resolve the problem. Record user names and other applications

Session is a technology that records user information on the server, and the session is used to share the data on the servers side.

2) How the cookie works and how the session works

The cookie works by looking at the diagram above that explains the cookie, which is sent back to the browser by server-side creation, and each time the request server brings the cookie over so that the server knows which one the user is.

It uses key-value pairs to store information in its cookie, and a cookie can store only one key-value pair. So when you get a cookie, you get all the cookies and then iterate through them .

      

The session works by relying on a cookie to support it, the session is created the first time you use Request.getsession (), and a unique SessionID is created for that session to be stored in a cookie. Then send it to the browser side,

Browser side each request, will take this SessionID, the server will know the SessionID, know SessionID find out which session. To achieve the purpose of sharing data. It is important to note that the session does not die as the browser shuts down, but instead waits for the timeout period.

Like on the point of a "recommendation" Oh!

Javaweb (ii) Session management in detail cookie and session

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.