Cookie, Session Silly Division is not clear

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/qq_15002323/article/details/51201597

What the hell is a cookie?

Well, as a Java web Little white, see the cookie a face to have no (⊙﹏⊙). Although the English poor don't want to, but still know this is a can eat cookies. What the heck? Session hold? Client storage? Better not let me understand, otherwise cut over you, ah pain! ~

Cookies, saying simple is a technique of saving information on the client. Give me a chestnut bar. ~~o (>_<) o ~ ~ In the browsing of certain Web pages, if you need to login, you enter the correct account and password after the successful login, the second visit to this landing page is not found that the account password has been populated by the system, even if restarting the computer, still so. This is the role of cookies.

So we're going to ask, how does a cookie come from, what exactly does it do, and I can make a very suitable metaphor here. At the weekend I went to a shopping mall to handle a VIP (^__^), the mall sent me a card, I went into the production of any consumption will be recorded in my card (of course, it is not possible to remember in the other card ah T), shopping malls do not know when I go to spend, do not know when I will leave after consumption , but that VIP card is my voucher. Maybe I have no intention of losing, I can go to the store to report the loss. Someone might have picked it up. But the VIP card related information is not known, serious suspicion of non-self, shopping malls can write off the voucher.

Well, to get to the point, in the above example, the mall sent me a VIP card is our cookie, where the mall is the server, I am the browser. O (∩_∩) o ha! There is no stone breaking the effect of the original cookie is still so ah.

In a nutshell, a Cookie is a token that the server makes to the client, and after the client receives the token (Set-cookie), it determines whether the relevant tag is created locally, based on a series of attribute values for that tag.

Say so much, let's have some dry goods. First write an empty servlet, configure the mapping, and then open the Firefox browser (why not chrome, I found that chrome in the cookie to see this a bit of a problem, obviously the local there is no way out, spit slot t^t) to visit this servlet to see the request section:

Look maybe confused is not, it doesn't matter, the important thing is that the cookie, this response header and the request head do not have this word--and then we make a slight change:

ImportJava.io.IOException;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.Cookie;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public  class cookietest extends httpservlet {    @Override    protected void Service(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8");//Set temporary cookie, only one session, default valueCookie Tempcookie =NewCookies ("Temp","Tempcookie"); Tempcookie.setmaxage (-1); Response.addcookie (Tempcookie);//Set instant cookie, browser receives cookie immediately deleteCookie cookie =NewCookies ("Cookie","666"); Cookie.setmaxage (0); Response.addcookie (cookie);//Set up resident cookiesCookie Usercookie =NewCookies ("User","CJT"); Usercookie.setmaxage ( -* -* -);    Response.addcookie (Usercookie); }}

You can see that we have written three cookies to the client, the notes are written clearly three different, and then we revisit the servlet:

Can be found in the response headers more than a Set-cookie Ah, this is the server to the client instructions, most browsers are support cookies, I use Firefox, you can open the menu in the upper right corner of the browser –> Option –> Privacy –> History –> drop-down box select Use custom history settings –> show cookies to view local saved cookies, there is also an easy way to enter URL access in the browser address bar, Click on the earth Small icon in front of the URL –> more information –> security –> view Cookies. Let's filter and see what we need:

You can see that there are two cookies on the local, temp and user,temp expire at the end of the browser session, and the user's expiration time is one day after the cookie is set to temporary, so it expires immediately, does not believe? Close all browser windows, then reopen the browser, look at the cookie again and discover that there is only one user value:

Write here should have a preliminary understanding of the cookie, say how to modify the existing cookie, because response inside only Addcookie method, so only a new cookie and then add in the way to take cover.

What the hell is the session?

Meng Ing~~~,cookie still not clear, the session is what ghost Ah, oh, to my careful way, bragging and not illegal (⊙o⊙).

In the previous section, the server distributed a cookie to the client, and then the client's second access server would pass the saved cookie back to the server intact, and if there were many cookies passed, this would increase the amount of data transferred, so that the session would appear.

When a client accesses a server (seemingly a Web page, the servlet does not, but if you write GetSession () in the servlet it can also appear!! ), the server typically distributes a jsessionid (Jsessionid = Session.getid (), expires at the end of the session) to the client, serves as a unique identifier for the client, and then the client is saved in the session cookie, saying no more, We create a new empty page newfile.jsp, access to see the effect:

I'm not kidding. By viewing the saved cookie value, you see that Jsessionid is a session cookie that refreshes the page:

This allows the client to find a HttpSession object previously created on the server by name Jsessionid, which is also known as a session trace. For a bit of code, create a new session servlet:

ImportJava.io.IOException;ImportJava.io.PrintWriter;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.Cookie;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportJavax.servlet.http.HttpSession; Public  class sessiontest extends httpservlet {    @Override    protected void Service(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8");        PrintWriter writer = Response.getwriter (); HttpSession session = Request.getsession ();//Set the session to a valid time of 1 daysSession.setmaxinactiveinterval ( -* -* -);if(Session.isnew ()) {Session.setattribute ("Name","CJT"); Writer.write ("New Session Success"); }Else{Writer.write (Session.getattribute ("Name"). ToString ()); }    }}

When the servlet is accessed for the first time, the browser outputs the word "new session Success", and when the page is refreshed, the previously saved "CJT" is output. It is worth saying that the session is stored on the server, so the browser does not control the creation and destruction of sessions, a session at the end is destroyed this sentence is not right. Just because the browser second access time Jsessionid changed (this is a session cookie), so through GetSession () is a new session, the previous temporary existence of the server, to the expiration time (by default, 20 minutes) automatically destroyed.

Compared to cookie,session is a lot simpler, I believe that if you seriously look down here hydrology, will certainly have a very familiar understanding of the cookie and session. (^o^)/~, before always know this piece, now finally understand, ruthless ~ ~

If someone asks you what the difference is between a cookie and a session, we can finally tell them loudly that the cookie is saved on the client and the session is saved on the server. However, the follow-up is to brag about them--.

about what cookies save Chinese, if the cookie is disabled by rewriting the URL to track the session, are well understood, encountered direct use on it, here is not detailed (I am really fine), to the end of the hydrology, worship a worship.

Cookie, Session Silly Division is not clear

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.