Java Web (iii) session mechanism, cookie and session details

Source: Internet
Author: User
Tags session id send cookies set time java web

A large part should know what is the session mechanism, but also can say a few words, I also probably know a little, but after a few days of learning, immediately forget, the reason may not be able to understand the two conversational mechanism, so will always forget, has been back to learn it, and today good to summarize him, Draw on the content of this article, because I think the article is really good, answered my many questions, characterized by the understanding of the cookie and session, in which the membership card example, really sharply. I follow my own ideas to rearrange a copy, to see for themselves later.

--wh

First, the session mechanism

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 .

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 sent (Just like talking after a phone call), is considered a session until the browser closes and the session ends. Note that a browser is the equivalent of a phone, if using Firefox, access to the server, is a session, and then open Google Browser, access to the server, this is another session, although the same computer, the same user in the access, but this is two different sessions.

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, and then click to browse the product, It seems like a normal operation to add a shopping cart to an item of interest and wait for the bill to be paid together, but think about it, if there are many other browsers on the computer that are also accessing the server of the shopping site, do something similar to us? Server is how to remember the user, how to know that user a purchase of any goods should be placed in a shopping cart, whether it is user a when purchased, can not be placed in User B or User C in the shopping cart? So there's the cookie and session technology, as the first line says, that cookies and sessions are used to keep track of the user's entire session,

The difference and connection between a cookie and a session

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 clerk is very strong, can remember each customer's consumption quantity, as long as the customer walked into the coffee shop, the clerk knew how to treat. This approach is the protocol itself that supports the state. But the HTTP protocol itself is stateless

2, issued to customers a card, the above record the amount of consumption, there is generally 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, 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 presented the card, 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. At the same time, we also see that because the server-side hold state of the scheme in the client also need to save an identity, so the session mechanism may need to use the cookie mechanism to achieve the purpose of saving the identity, but in fact it has other options

Second, 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 membership card, membership card content: that is, how to create a cookie? 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

Cookie cookie = new Cookie (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 the customer uses the membership card, how the cookie works on the client, what is the working principle?

        

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, and there is no more.

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 cookies. Regardless of the previous expiry=-1 or expiry>0, when setting the expiry=0, the cookie will be deleted by the browser.

    

4. What is the application scope of 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 the cookie.

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 can get to cookie,/test01/a/b/c/myservlet this myservlet to get a cookie.

Modifying access paths for cookies

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

Thoroughfare: 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.

5. Summary cookie:

Work Flow:

1. The 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.

Cookie manipulation

1. Create Cookie:new Cookie (name,value)

2. Send cookie to Browser: Httpservletresponse.addcookie (cookie)

3.servlet receive Cookie:HttpServletRequest.getCookies () All cookies sent by the browser

Cookie Features

1. Each cookie file size: 4kb, if more than 4KB browser does not recognize

2. One Web site (Web project): Send 20

3. Total size of a browser: 300

4.cookie is unsafe and may reveal 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

Cookie API

GetName () Get the name, key in the cookie

GetValue () Gets the value, in the cookie

SetValue (java.lang.String newvalue) sets the content to modify the value of the key.

Setmaxage (int expiry) Set valid time ""

SetPath (java.lang.String URI) set path ""

SetDomain (java.lang.String pattern) set the domain name, generally invalid, have the browser automatically set, SetDomain (". itheima.com")

Www.itheima.com/bbs.itheima.com can access

A.b.itheima.com Cannot access

Role: Set the scope of the cookie, the domain name + path together constitutes the scope of the cookie, the above setpath is useful, because there is a browser automatically set the domain name properties, but we must know that there is such a property to set the domain name

Ishttponly () is only used by the HTTP protocol. Only servlets are obtained through getcookies () and JavaScript is not available.

Setcomment (java.lang.String Purpose) (understanding)//information describing the cookie (description), which can be seen when the browser displays cookie information

SetSecure (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.

The setversion (int v) (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 tools to encode

Urlencoder: Encoding

Urldecoder: Decoding

Send cookies

Cookie cookie = new Cookie (urlencoder.encode ("haha"), Urlencoder.encode ("hehe"));

Response.addcookie (cookie);

Get cookie content in Chinese

Urldecoder.decoder (Request.getcookie (). GetName); Get key

Urldecoder.decoder (Request.getcookie (). GetValue); Get value

6.cookie case

6.1, remember the 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, and then the next time the browser visits the login page, the first to get a cookie, the information in the cookie to see if the user name is saved, if saved, So directly with him, if not, then write your own user name.

6.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.

Third, Session

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 presented the card, the shop clerk in the store's records found this 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: The server is used to share data technology,

            

Session Principle Analysis:

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 generates a session that is associated with this session Id,sessionid value should be a string that is neither duplicated nor easily found to mimic the pattern. This sessionid will be returned to the client in this response to save, the way to save this sessionid can be a cookie, so in the process of interaction, the browser can automatically follow the rules to send this identity back to the server, The server according to this sessionid can find the corresponding session, and back to the beginning of the text.

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

Session Property Operation:

Xxxattribute (...)

Used to hold some information before sharing information

Setattrubute (Key,value);

GetAttribute (key);

     

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. For the session is the same, unless the program notifies the server to delete a session, or the server will remain, the program is generally in the user to log off when sending an instruction to delete the session. However, the browser will never proactively notify the server before shutting down, so the server will not have the opportunity to know that the browser has been shut down, the reason for this illusion is that most of the session mechanism uses a conversation cookie to save the sessions ID, The session ID disappears when you close the browser, and you cannot find the original session when you connect to the server again. If the cookie set by the server is saved to the 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 to still find the original session

It is precisely because closing the browser does not cause the session to be deleted, forcing the server to set an expiration time for seesion, typically 30 minutes, when the client last time to use the session more than the expiration time, the server can assume that the client has stopped the activity, The session is deleted to save storage space

We can also control the duration of the session on our own.

Session.invalidate () destroys the Session object

Setmaxinactiveinterval (int interval) Set the effective time, in seconds

Configure the session's effective time in Web. xml

<session-config>

<session-timeout>30</session-timeout> units: Minutes

<session-config>

    

So, the discussion is that the life cycle of the session is:

Created: First call to GetSession ()

Destroyed:

1, timeout, default 30 minutes

2, the execution Api:session.invalidate () The Session object destruction, Setmaxinactiveinterval (int interval) Set the effective time, units per second

3, the server is not properly shut down

Kill yourself and shut down the JVM right away.

If you shut down normally, the session 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

URL Rewrite 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

Manual way: url;jsessionid= ....

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 links to be accessed may be redirect to other servlets for processing. This way, the ID information of the session you bring with the above method cannot be transmitted to other servlets at the same time. Use the Encoderedirecturl () method to

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

Note: If your browser disables all URLs for cookie,web items, you need to override them. Otherwise the session will not work properly

When a cookie is banned,

                

Iv. Summary

Know what a cookie is and what is a 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

The session is a technique for recording user information on the server side, which is used to share data

How does a cookie work? How does the session work?

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 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.

  

If there is no understanding of the cookie and the session, it will be used by everyone, that is to understand, why you need to use cookies and session, you can see the example of the membership card, Cookies and sessions are only intended to address this flaw in the stateless HTTP protocol, in order to record user information, record the state between the browser and the server and derive it.

        

Java Web (iii) session mechanism, cookie and session details

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.