Java Cookie Explanation

Source: Internet
Author: User
Tags html form

Reprint: http://www.360doc.com/content/12/1125/17/820209_250155635.shtml

I. What is a cookie? As you know, the browser communicates with the Web server using the HTTP protocol, and when a user makes a page request, the Web server simply responds and then closes the connection to that user. So when a request is sent to a Web server, whether or not it is the first visit, the server treats it as if it were the first time, which is a bad thing to imagine. To compensate for this flaw, Netscape has developed a cookie as an effective tool to keep a user's identifying information, so people are nicknamed "cookies." Cookies are a means by which a Web server stores information on a visitor's hard disk via a browser: Netscape Navigator uses a local file called Cookies.txt to hold cookie information received from all sites, while IE stores cookie information in a directory similar to c://windows//cookies. When a user accesses a site again, the server will ask the browser to find and return the cookie information previously sent to identify the user.
Cookies offer a great many benefits to websites and users:
1. Cookies enable the site to track the number of visits to a particular visitor, the last access time, and the path of the visitor to the site
2. Cookies can tell the number of times an online advertiser has been clicked, thus allowing more accurate advertising
3, when the cookie expires, the cookie allows the user to enter some sites that have been browsed without typing the password and username.
4, cookies can help the site to statistical users of personal data to achieve a variety of personalized services
In JSP, we can also use cookies to write some powerful applications.
Below, I would like to explain how to create and process cookies using JSPs.
two. How to create a cookie
import= "Javax.servlet.http.Cookie"
Having said so much, you must be very interested to know how JSP is creating cookies. The JSP uses the following syntax format to create a cookie:
Cookie Cookie_name =new Cookie ("Parameter", "Value");
For example:
Cookie Username_cookie =new Cookie ("username", "Waynezheng");
Response.addcookie (Username_cookie);
Explanation: A JSP is a corresponding constructor cookie (Name,value) that invokes a cookie object to create a cookie with the appropriate name and value, and thencookies can be added to the Set-cookie answer header via the HttpServletResponse Addcookie method,
In this case, the cookie object has two string arguments: Username,waynezheng. Note that both the name and the value cannot contain white space characters and the following characters: @:;? , " / [ ] ( ) =
Handling properties of cookies

See here, some friends ask again: I just know how to create a cookie what is the use? Yes, it's not enough to know how to create a cookie without knowing how to use it.
In JSP, the program is to set various properties through COOKIE.SETXXX, using Cookie.getxxx to read the properties of the cookie, now the main attributes of the cookie, and its methods are listed below for your reference:

Type
Method name
Method explanation

String getcomment () returns a comment in the cookie that returns a null value if there is no comment.

String GetDomain () returns the domain name that the cookie applies to in the cookie. Use the GetDomain () method to instruct the browser to return the cookie to another server in the same domain, and usually the cookie is returned only to the server that is exactly the same name as the server that sent it. Note that the domain name must start with a point (for example,. yesky.com)

int Getmaxage () returns the maximum time, in seconds, before the cookie expires.

String GetName () returns the name of the cookie. The name and value are the two parts that we always care about, the author will introduce getname/setname in detail later.

String GetPath () returns the path to which the cookie applies. If you do not specify a path, the cookie is returned to all pages in the same directory as the current page and its subdirectories.

Boolean getsecure () returns a true value if the browser sends a cookie via a security protocol, or False if the browser uses a standard protocol.

String GetValue () returns the value of the cookie. The author will also introduce getvalue/setvalue in detail later.

int GetVersion () returns the protocol version that the cookie complies with.

void Setcomment (String purpose) Sets the comment in the cookie.

void SetDomain (String pattern) sets the domain name that the cookie applies to in the cookie

void setmaxage (int expiry) is calculated in seconds to set the cookie expiration time.

void SetPath (String uri) specifies the path to which the cookie applies.

void SetSecure (Boolean flag) indicates the security protocol used by the browser, such as HTTPS or SSL.

The void SetValue (String newvalue) cookie is created after a new value is set.

void setversion (int v) Sets the protocol version that the cookie complies with.

read Client's Cookie
Before the cookie is sent to the client, create a cookie and then send an HTTP Header using the Addcookie method. The JSP calls Request.getcookies () from the client read-in Cookie,getcookies () method to return the contents of an HTTP request header corresponding to thearray of Cookie objects。 You only need to iterate through the elements of the array, call the GetName method to check the name of each cookie until the target cookie is found, and then call the GetValue method on the cookie to get the value associated with the specified name.
For example
<%
Obtained from the submitted HTML form, the user name
String username=request.getparameter ("UserName");
Create a cookie with "username", username value/pair
Cookie Theusername=new Cookie ("username", username);
Response.addcookie (Theusername);
%>
..............
<%
Cookie mycookie[]=request.getcookies ();//Create an array of cookie objects
for (int n=0;n=cookie.length-1;i++);//Set up a loop to access each element of a cookie object array
Cookie newcookie= Mycookie[n];
if (Newcookie.getname (). Equals ("username")); Determines whether the value of an element is a value in username
{%>
Hello, <%=newcookie.getvalue ()%>!//If you find it, say hello to him.
<%}
%>
set the time the cookie exists and delete cookies
In JSPs, the setmaxage (int expiry) method is used to set the time the cookie exists, and the parameter expiry 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 the cookie will be present, not the time the cookie is present. A negative value indicates that the cookie will be deleted when the browser is closed. A value of 0 is the cookie to be deleted. Such as:
<%
Cookie Deletenewcookie=new Cookie ("Newcookie", null);
Deletenewcookie.setmaxage (0); Delete this cookie
Deletenewcookie.setpath ("/");
Response.addcookie (Deletenewcookie);
%>
First, preface
In other words, cookies should be a long-applied technology. There is no way to record and identify different users between each individual page as early as the HTML has just appeared. Later, people invented the cookie technology, when the user visited the Web page, it can create a file on the visitor's machine, we call it a cookie, write a piece of content to identify different users. If the next time the user accesses this page, it will be able to read the contents of the file, so that the page will know the last time the user has visited the page.
Although the production of Web pages today is much more developed than it was a few years ago. But sometimes, cookies can help us a lot. Next, let's take a look at how to use JSP to manipulate cookies when writing JSP files.
=======================================
Second, save write cookie
In fact, using JSP to manipulate cookies is very simple, we look at the following a JSP program:
........ (Middle slightly)
SaveWrite Cookie
<%
String cookiename= "Sender";
Cookie Cookie=new Cookie (cookiename, "test_content");
Cookie.setmaxage (10); Survival time is 10 seconds
Response.addcookie (cookie);
%>
........ (Other content)
So we've set up a cookie, is that simple?
Let's take a closer look at this piece of code:
Cookie Cookie=new Cookie (cookiename, "test_content");
This line establishes a cookie object initialized with two parameters, the first parameter cookiename defines the name of the cookie, the latter argument, and a string that defines the contents of the cookie. That is, the file content that we want the page to identify on the user's machine.
Next line: Cookie.setmaxage (10), called the Setmaxage method in the cookie, sets the lifetime of the cookie on the user's machine's hard drive to 10 seconds. The time that a cookie exists in the user's hard drive is not indefinite, and when the cookie object is created, we must establish the lifetime of the cookie, beyond which the cookie file ceases to function and is deleted by the user's browser. If we want the user to visit this page the next time the cookie file is still valid and can be read by the Web page, we can set the lifetime of the cookie a little longer. For example, Cookie.setmaxage (365*24*60*60) allows a cookie file to be valid for a period of one year.
third, read the cookie
After the cookie file is created, naturally we need to read it out, otherwise we are not in vain. Next we look at how to read the cookie on the user's hard drive.
........ (Middle slightly)
Name value
<%
Cookie cookies[]=request.getcookies (); Read the cookie on the user's hard drive and place all cookies in an array of cookie objects
Cookie Scookie=null;
String Svalue=null;
String Sname=null;
for (int i=0;i<cookies.length-1;i++{//using a looping statement to iterate over the array of cookie objects just created
Scookie=cookies; Remove a cookie object from the array
Sname=scookie.getname (); Get the name of this cookie
Svalue=scookie.getvalue (); Get the content of this cookie
%>
<%
}
%>
Name value
<%=name%> <%=svalue%>
........ (Other content)
This small JSP file can read out all valid cookies on the user's hard drive, which is the cookie file that is still in existence for the time being. Lists the names and contents of each cookie in the form of a table.
Let's analyze this code on a row-by-line basis:
Cookie cookies[]=request.getcookies () we use request.getcookies () to read the cookie on the user's hard drive and place all cookies in an array of cookie objects.
Next we use a looping statement to iterate over the array of cookie objects just created, and we use the Scookie=cookiesTake out a cookie object in the array, and then we use Scookie.getvalue () and Scookie.getname () two methods to get the name and content of the cookie.
By placing the names and contents of the extracted cookies in a string variable, we can do all sorts of things. In the example above, all the cookies can be displayed in a single table by iterating through the loop statements.
=======================================
Iv. Some issues needing attention
With the two simple examples above, it is easy to see how cookies are manipulated using JSP. However, we should also pay attention to some problems in the actual operation:
1. Compatibility issues with Cookies
The format of the cookie has 2 different versions, the first version, which we call Cookie version 0, was originally developed by Netscape and is supported by almost all browsers. The newer version, Cookie version 1, is based on the RFC 2109 documentation. In order to ensure compatibility, Java stipulates that the previously mentioned actions involving cookies are for older versions of cookies. The new version of the cookie is not currently supported by the Javax.servlet.http.Cookie package.
2. Contents of Cookies
The same cookie content has a different character limit for different cookie versions. In Cookie Version 0, certain special characters, such as: space, square brackets, parentheses, equals sign (=), comma, double quotation mark, Slash, question mark, @ symbol, colon, semicolon cannot be the contents of a cookie. This is why we set the content of the cookie as "test_content" in the example.
Although the restrictions are relaxed in the cookie version 1 provisions, these characters can be used, but given that the new version of the cookie specification is still not supported by all browsers, we should try to avoid using these characters in the content of the cookie as far as it is safe to do so. (

Java Cookie Explanation

Related Article

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.