Shopping Cart cookie1

Source: Internet
Author: User

1. What are cookies?

As we all know, the browser communicates with the Web server over HTTP. When a user sends a page request, the web server simply responds, close the connection to the user. Therefore, when a request is sent to the Web server, whether it is the first visit or not, the server treats it as the first visit. Such a bad thing can be imagined. To make up for this defect, Netscape has developed an effective cookie tool to store the recognition information of a user. Therefore, they are nicknamed "cookies ". Cookies are a means for Web servers to store information on visitors' hard disks through Browsers: Netscape navigatoruses a local file named cookies.txt to store Cookie Information received from all sites; the IE browser saves the cookie information in a directory similar to c: \ windows \ cookies. When a user accesses a site again, the server requires the browser to search for and return the cookie information sent previously to identify the user.
Cookies bring many benefits to websites and users:
1. Cookie allows the site to track the number of visits, the last visit time, and the path of visitors to the site
2. Cookies can tell online advertisers the number of clicks on ads, so that they can deliver ads more accurately.
3. When the cookie validity period is not reached, the cookie enables users to access some websites they have browsed without entering their passwords and usernames.
4. Cookies can help Websites collect users' personal data for various personalized services.

In JSP, we can also use cookies to write some powerful applications.
Next, I would like to introduce how to use JSP to create and process cookies.

Ii. How to Create a cookie
After talking about this, you must be curious about how JSP creates cookies. JSP uses the following syntax format to create a cookie:
Cookie cookie_name = new cookie ("parameter", "value ");
For example, Cookie newcookie = new cookie ("username", "waynezheng"); response. addcookie (newcookie );
Explanation: JSP calls the constructor cookie (name, value) corresponding to the cookie object to create a cookie with a proper name and value, then, the cookie can be added to the Set-Cookie response header Through the addcookie method of httpservletresponse. In this example, the cookie object has two string parameters: username and waynezheng. Note that the name and value cannot contain white spaces or the following characters :@:;? , "/[] () =
  Process cookie attributes 
Some friends have asked me again: I know how to create cookies? Yes, it is not enough to know how to create a cookie without knowing how to use it. In JSP, the Program sets various attributes through cookie. setxxx and reads the cookie attributes using cookie. getxxx. The main attributes and methods of the cookie are listed below for your reference:

Type Method Name Explanation
String Getcomment () Return the comment in the cookie. If there is no comment, a null value is returned.
String Getdomain () Returns the domain name applicable to the cookie in the cookie. the getdomain () method can be used to instruct the browser to return the cookie to other servers in the same domain. Generally, the cookie only returns the server with the same name as the server that sent the cookie. Note that the domain name must start with a dot (for example, .yesky.com)
Int Getmaxage () Returns the maximum time before the cookie expires, in seconds.
String Getname () Returns the cookie name. The name and value are two parts that we always care about. The author will introduce getname/setname in detail later.
String Getpath () Return the applicable path of the cookie. If no path is specified, the cookie will be returned to all the pages in the directory of the current page and Its subdirectories.
Boolean Getsecure () If the browser sends cookies through the security protocol, the return value is true. If the browser uses the standard protocol, the return value is false.
String Getvalue () Return the cookie value. The author will also introduce getvalue/setvalue in detail later.
Int Getversion () Return the Protocol version that the cookie complies.
Void Setcomment (string purpose) Set the comment in the cookie.
Void Setdomain (string pattern) Set the domain name for the cookie in the cookie
Void Setmaxage (INT expiry) Set the cookie expiration time in seconds.
Void Setpath (string URI) Specifies the applicable path of the cookie.
Void Setsecure (Boolean flag) Indicates the security protocol used by the browser, such as https or SSL.
Void Setvalue (string newvalue) Set a new value after the cookie is created.
Void Setversion (int v) Set the Protocol version that the cookie complies.

Read client cookies

Before sending a cookie to the client, you must create a cookie and then use the addcookie method to send an HTTP header. JSP will call request. getcookies () to read the cookie from the client. The getcookies () method returns an array of cookie objects corresponding to the content in the HTTP request header. You only need to access each element of the array cyclically, call the getname method to check the names of each cookie until the target cookie is found, call the getvalue method for the cookie to obtain the value associated with the specified name.
For example 

<% String username = request. getparameter ("username"); // obtain from the submitted HTML form, username cookie theusername = new cookie ("username", username); // use "username ", username value/create a cookie response for the pair. addcookie (theusername); %> .............. <% cookie mycookie [] = request. getcookies (); // create a cookie object array for (INT n = 0; n = cookie. length-1; I ++); // sets up a loop to access each element of the cookie object array. Cookie newcookie = mycookie [N]; If (newcookie. getname (). equals ("username" ); // Determine whether the element value is in username {%> hello, <% = newcookie. getvalue () %>! // If yes, send "hello" to him <%} %>

Set the cookie existence time and delete the cookie in JSP. Use the setmaxage (INT expiry) method to set the cookie existence time. The expiry parameter should be an integer. A positive value indicates that the cookie will expire after so many seconds. Note that this value is the maximum time for the cookie to exist, rather than the current time when the cookie exists. A negative value indicates that when the browser is closed, the cookie will be deleted. If the value is zero, the cookie is to be deleted. For example:

<% Cookie deleteNewCookie=new Cookie("newcookie",null); deleteNewCookie.setMaxAge(0); deleteNewCookie.setPath("/");  response.addCookie(deleteNewCookie);%>

Tested and verified in Firefox, ie, and Google Chrome. For commas (,), spaces, semicolons (;), and $ headers. The cookie cannot be written normally, so encode must be encoded.

Note: I thought I could understand the above, but I can use it after I finish it. But the next day when my colleague calls the cookie on another page (not the page that generates the cookie, from the debug perspective, I have never added any cookies. I learned from the Internet that my cookies have two important settings: setmaxage () and setpath (); when you need to modify the quantity of your shopping cart or add the quantity to it, you need to get the cookie first, but the Cookie obtained at this time, check their maxage and path attributes. You will find that they are not set by you. At first, I was not too clear, and later I figured it out, response. addcookie is used to create a cookie file locally. When you obtain the file, maxage and path cannot exist. Because maxage is obtained, it will not expire, in other words, the default value of path is setpath = "/", but I cannot get this cookie because I did not write this other page in the program. Added. So when you modify the cookie, remember to write it again. setmaxage (); cookie. setpath ("/'); response. addcookie (cookie );

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.