Cookie summary and small application of cookies

Source: Internet
Author: User

Cookie summary and small application of cookies

will be words (Session) tracking is a common technique used in Web applications 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 .

Cause:

in the program, session tracking is a very important thing. the Web server-side program is able to distinguish from a large number of request messages which request messages belong to the same session, that is, to identify access requests from the same browser, which requires the browser to identify each request message that it sends out : Request messages that belong to the same session are accompanied by the same identification number, and the request message that belongs to a different session always comes with a different identification number, which is called the session ID (SessionID)

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.

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

Cookie mechanism:

The cookie mechanism uses a scheme that maintains HTTP state information at the client? A cookie is a resource that is accessed by a Web server in the HTTP Response message header when a browser accesses a Web server A small text file that is shipped to the browser . ? Once a cookie is saved by the Web browser, it will be in the HTTP request Header each time it accesses the Web server. Cookies To pass back to WEB Server . 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, and the browser adds The cookie request Header field passes the cookie back to the Web server. ? A cookie can only identify a single message that contains at least one name and set value (value) that identifies the information. ? A Web site can send multiple cookies to a Web browser, and a Web browser can store cookies provided by multiple Web sites. The browser generally allows only 300 cookies, with a maximum of 20 cookies per site and a limit of 4KB per cookie size.
The following is the cookie transfer process

using cookies in a servlet program ? 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. ? Methods of the cookie class:Construction Method: Publiccookie (Stringname,stringvalue) getName method SetValue and getValue method setmaxage and getmaxage method SetPath and GetPath method? 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. ? 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.
take 2 small programs to illustrate the use of cookies1. Automatic landing page:– no information such as user name and password is required and can be automatically logged into the system start by writing a simple JSP page:
<formaction = "index.jsp" method= "POST" >name: <inputtype= "text" name= "name"/><inputtype= "Submit" Value= "Submit"/><pre name= "code" class= "Java" ></form>

That's probably it.:simply enter a name, click on the login, the page can be in a certain period of time without entering the name to log in. So what should the index.jsp code say?
<%//gets the value of the Name property passed in As String value =request.getparameter ("name");//The judgment is not NULL if (value!=null&&!value.trim (). Equals ("")) {//with "name" and this value to create a cookie instantiation object needs to be passed into a key-value pair. Key=name;value=valuecookie Cookie =new Cookie ("name", value);//The method sets the time that the cookie exists, indicating the presence of 30scookie.setmaxage (30); Insert the cookie into the HTTP response header. Response.addcookie (cookie);} else{//follow-up visits, you can get the requested Cookiescookie [] cookies =request.getcookies (); if (Cookies!=null &&cookies.length>0 {//Traversal of the cookie array, because it may contain many different cookie information//need to find key=name corresponding value.for (Cookie cookie:cookies) {String cookiename = Cookie.getname (); if ("Name". Equals (CookieName)) {String value2 =cookie.getvalue (); Value =value2;}}}} If the name exists, print the login information directly if (value!=null&&!value.trim (). Equals ("")) {out.println ("Hello:" +value);} else {//Otherwise call redirect, return the page to the initial page response.sendredirect ("login.jsp");} %>

and then you can use it. There is also a small program:Displays the title of the most recently viewed 5 skill there is a books.jsp and a book.jsp. A page is responsible for displaying all the books. A specific description of a particular book was written. Click on one of the books.jsp's books, go to the corresponding book.jsp page, and then return to the title of the recently viewed book below the books.jsp page. The initial books.jsp:
BOOK.JSP:
you will then need to display the most recent browsing history below the books.jsp page, so add the following code to boos.jsp:  
<%//Show the most recently viewed 5 books//Get all the Cookiecookie [] cookies=request.getcookies ();//filter out the book cookie, If the cookiename is Atguigu the beginning of the match condition if (Cookies!=null &&cookies.length>=0) {for (Cookie c:cookies) {String  Cookname =c.getname (), if (Cookname.startswith ("book")) {Out.println (C.getvalue ());}}} %>
This completes a small program that displays the records of the 5 books that have been viewed recently. There are, of course, many areas that need to be perfected.







Cookie summary and small application of cookies

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.