Javaweb Cookie Explanation

Source: Internet
Author: User

The code address is as follows:
Http://www.demodashi.com/demo/12713.html

The origin of the cookie

First we need to explain why cookies are introduced in the Web development process. We know that the HTTP protocol is a stateless protocol,
The Web server itself does not recognize which requests are made by the same browser, and every request from the browser is completely orphaned.
Even if the Http1.1 supports persistent connections, the connection is automatically closed when the user has not submitted a request for a period of time. At this point, as a Web server,
A mechanism must be used to uniquely identify a user and to record the state of that user. The first mechanism is introduced: the cookie mechanism.

Cookie mechanism: The scenario in which HTTP status is maintained on the client is used.

The definition of a cookie is a basic introduction

Cookies are when a browser accesses a resource on a Web server,
A small text file that is delivered to the browser by the Web server in the HTTP response message header.

    1. Once a Web browser has saved a cookie,
      Then every time it accesses the Web server,
      Will pass this cookie back to the Web server in the HTTP request header.
    2. A cookie can only identify one type of information,
      It contains at least one name and set value (value) that identifies the information.
    3. A Web site can send multiple cookies to a Web browser,
      A Web browser can also store cookies provided by multiple Web sites.
    4. Browsers generally allow only 300 cookies to be stored,
      Each site holds up to 20 cookies, each with a size limit of 4KB.
The principle of cookies

The underlying implementation principle: The Web server sends cookie information to the browser by adding the Set-cookie response Header field in the HTTP response message.
The browser passes the cookie back to the Web server by adding a cookie request header field to the HTTP request message.

The process of transferring cookies

The use of cookies in Javaweb
    1. A Javax.servlet.http.Cookie class is provided in the Servlet API to encapsulate cookie information, which contains methods for generating cookie information and extracting individual attributes of cookie information.
    2. Methods of the Cookie class:
      • Construction method: Public Cookie (String name,string value)
      • GetName method
      • SetValue and GetValue method
      • Setmaxage and Getmaxage method
      • SetPath and GetPath method
    3. A Addcookie method is defined in the HttpServletResponse interface that is used to add a Set-cookie response header field to the HTTP response message sent to the browser.
    4. The HttpServletRequest interface defines a getcookies method that is used to read all cookie entries from the cookie Request header field of an HTTP request message.
Sending of cookies
    1. Create a Cookie Object
    2. Set Maximum Aging
    3. Put a cookie into the HTTP response header
      • If a cookie is created and sent to the browser, by default it is a session-level cookie; stored in the browser's memory and deleted after the user exits the browser.
        If you want the browser to store the cookie on disk, you need to use maxage and give a time in seconds. Setting maximum aging to 0 is the command browser to delete the cookie.
      • Sending a cookie requires the use of the HttpServletResponse Addcookie method to insert the cookie into a Set-cookie HTTP response header.
        Since this method does not modify any of the previously specified Set-cookie headers, it creates a new header, so this method is called Addcookie, not Setcookie.
Reading of Cookies
    1. Call Request.getcookies to get the cookie sent by the browser, you need to call HttpServletRequest's GetCookies method,
      This call returns an array of cookie objects that correspond to the values entered by the cookie header in the HTTP request.
    2. Loops the array, invoking the GetName method of each cookie until it finds the cookie of interest.
The difference between a session cookie and a persistent cookie
    1. If you do not set an expiration time, the cookie disappears when the browser window is closed as long as the cookie's lifetime is the browser session.
      This cookie, which is the lifetime of the browser session, is referred to as a session cookie.
      Session cookies are generally not saved on the hard disk but in memory.
    2. If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and these cookies remain valid until the set expiration time expires.
      Set Expiration Time: Setmaxage (param) param is the specific time, in seconds.
    3. Cookies stored on the hard disk can be shared between different browser processes,
      For example, two IE windows. For cookies stored in memory, different browsers have different ways of handling them.
Specific implementation

Implementing the Automatic Logon process

Normal login enters the page, name is present in String name = Request.getparameter ("name");        String check = Request.getparameter ("checked");            if (name = = NULL | | name.equals ("")) {//To determine that the Cookie does not exist cookie[] cookies = request.getcookies ();                    if (cookies = null && cookies.length > 0) {for (Cookie cookie:cookies) {                    String cookiename = Cookie.getname ();                        if (Cookiename.equalsignorecase ("Demoname")) {name = Cookie.getvalue ();                    Break }}}//does not exist stating that the cookie expires or is illegal to access, otherwise output the correct content if (name = = NULL | | name.equals ("")             ) {Response.sendredirect ("demo1.jsp");                } else{Cookie cookie = new Cookie ("Demoname", name);                Cookie.setmaxage (60);    Response.addcookie (cookie);//Set persistent cookie, stored on disk out.println ("Hello" + name + "\ n");            Out.println (System.currenttimemillis ()); }}else{if (check! = null && check.equalsignorecase ("on")) {Cookie cookie = new C                Ookie ("Demoname", name);            Cookie.setmaxage (60);//Set Persistent cookie Response.addcookie (cookie);            } out.println ("Hello" + name + "\ n");        Out.println (System.currenttimemillis ()); }

Implementing the most recent browsing history function

The information in the book is passed back to the browser in a cookie, deleting a cookie//1. Determine the number of cookies to be deleted beginning with a value greater than or equal to 5,//and delete the older Cooki if the book passed from the books.jsp page does not tommyyangcn the beginning of the COOKIE:TOMMYYANGCN cookie collection E (the first cbookie of a collection of cookies beginning with TOMMYYANGCN), in which case the cookie//2 is deleted.         Returns the book passed from Books.jsp as a Cookie to the final String cookiefinalname = "TOMMYYANGCN";        Use the List (queue mechanism) to store cookies, the first one is the longest access list<cookie> Booklist = new arraylist<cookie> ();        String bookname = Request.getparameter ("BookName");        Out.print ("Welcome to watch Online:" + bookname);        cookie[] cookies = request.getcookies ();        Cookie Tempcookie = null; if (cookies = null && cookies.length > 0) {for (Cookie cookie:cookies) {Strin                G Thiscookiename = Cookie.getname ();                The storage space to populate the cookie if (Thiscookiename.startswith (Cookiefinalname)) {booklist.add (cookie); }//See if the current book is in the cookie array if (cookie.getValue (). Equals (BookName)) {Tempcookie = cookie; }}}//indicates that the current book is not in the cookie array, the current book is added to the most recently viewed cookie array, and the longest-visited book is deleted, for the list collection, the first if (Tempcook        ie = = null && booklist.size () > 0) {tempcookie = Booklist.get (0); }//TOMMYYANGCN the number of cookies that begin with is greater than or equal to 5, delete the cookie that needs to be deleted, that is Tempcookie if (booklist.size () >= 5 && Tempcoo            Kie = null) {tempcookie.setmaxage (0);        Response.addcookie (Tempcookie);        } Cookie cookie = new Cookie (cookiefinalname + bookname, bookname); Response.addcookie (cookie);
How to Run code
    1. Clone the code locally, use Eclipse to import the code, and, when importing, choose Git project for the type of project.
    2. Right-click the project run on Server.

Law II: Copy the contents of WebContent in the project into your TOMCCAT server under the WebApps directory you built the site name,
Then start the Tomcat server,
Enter in the browser: http://localhost:8080/site name, you can access

The WebApps directory under the Tomcat directory is as follows:

Site page Show

Project file Structure

Javaweb Cookie Explanation

The code address is as follows:
Http://www.demodashi.com/demo/12713.html

Note: This copyright belongs to the author, by the demo master, refused to reprint, reprint need the author authorization

Javaweb Cookie Explanation

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.