JSP cookie Usage Details

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 and closes
Connection to this 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 the effective cookie tool to store the recognition information of a user. Therefore, they are nicknamed "cookies ". Cookies are a type
The method by which the browser stores information on the visitor's hard disk: Netscape
Navigatoruses a local file named cookies.txt to save the cookie information received from all sites. The IE browser saves the cookie information similar
C: // windows // cookies directory. When a user accesses a site again, the server requires the browser to search for and return the cookie information sent previously to identify this
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

Import = "javax. servlet. http. 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 username_cookie = new cookie ("username", "waynezheng ");
Response. addcookie (username_cookie );

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 the corresponding content in the HTTP Request HeaderCookie object Array. 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
<%
// Obtain the username from the submitted HTML form
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 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"); // determines whether the element value is a value in username.
{%>
Hello, <% = newcookie. getvalue () %>! // If you find it, say 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); // Delete this cookie
Deletenewcookie. setpath ("/");
Response. addcookie (deletenewcookie );
%>

I. Preface

Cookie should be a technology that has been used for a long time. As early as the advent of HTML, there was no way to record and identify different users between each independent page. Later, people invented
Cookie technology: when a user accesses a webpage, it can create a file on the visitor's machine. We call it Cookie and write a piece of content to identify different users. If the next user
When you access the webpage again, it can read the content in the file again, so that the webpage knows that the user has visited the webpage last time.

Although the current web page production technology has developed much more than a few years ago. However, sometimes cookies can help us a lot. Next, let's take a look at how to use JSP to operate cookies when writing JSP files.
========================================================

Ii. Save and write the cookie

In fact, using JSP to operate cookies is very simple. Let's look at the following JSP program:

... (Omitted in the middle)

// SaveWrite cookie
<%
String cookiename = "sender ";
Cookie = new cookie (cookiename, "test_content ");
Cookie. setmaxage (10); // The storage period is 10 seconds.
Response. addcookie (cookie );
%>
...... (Other content)

In this way, we set a cookie. Is it easy?

Let's take a closer look at this Code:

Cookie = new cookie (cookiename, "test_content ");

This line creates a cookie object with two initialization parameters. The first parameter cookiename defines the cookie name, and the last parameter is also a string that defines the cookie content. That is, the file content we want the webpage to identify on the user's machine.

Next line: Cookie. setmaxage (10). The setmaxage method in the cookie is called to set the survival of the cookie on the hard disk of the user's machine.
The period is 10 seconds. A cookie does not exist on the user's hard disk for an indefinite period of time. When creating a cookie object, we must specify the cookie retention period.
After the cookie file is saved, it will no longer work and will be deleted by the user's browser. If we want the user to access this page next time, the cookie file will still be valid and
If the page is read, we can set the cookie retention period to a little longer. For example, Cookie. setmaxage (365*24*60*60) can make the cookie file valid within one year.

3. Read and retrieve cookies

After the cookie file is created, we still need to read it. Otherwise, isn't it a waste of effort? Next, let's take a look at how to read the cookies on the user's hard disk.

... (Omitted in the middle)

NAME value

<%
Cookie Cookies [] = request. getcookies (); // read the cookies on the user's hard disk and put all the 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 ++ {// use a loop statement to traverse the cookie object array just created
Scookie = Cookies [I]; // retrieves a cookie object from the array.

Sname = scookie. getname (); // get the cookie name
Svalue = scookie. getvalue (); // get the cookie content
%>

<%
}
%>

NAME value
<% = Name %> <% = svalue %>

...... (Other content)

This small JSP file can read all valid cookies on the user's hard disk, that is, the cookie files that are still in use. List the names and contents of each cookie in a table.

Let's analyze this code line by line:
Cookie Cookies [] = request. getcookies () We use request. getcookies () to read the cookies on the user's hard disk and put all the cookies in an array of cookie objects.
Next, we use a loop statement to traverse the cookie object array we just created. We use scookie = Cookies [I] to retrieve a cookie object in the array. Then we
Use scookie. getvalue () and scookie. getname () to obtain the cookie name and content.

By placing the obtained cookie name and content in the string variable, we can perform various operations on it. In the preceding example, all cookies can be displayed in a table through loop statement traversal.
========================================================

4. Notes

The preceding two simple examples show that it is very simple to use JSP to perform cookie operations. However, we should pay attention to the following issues in actual operations:

1. Cookie compatibility

The cookie format has two different versions. The first version is called Cookie version.
0 was originally developed by Netscape and supported by almost all browsers. The newer version, Cookie version 1, is based on RFC
2109 developed in the document. To ensure compatibility, Java stipulates that all the cookie-related operations mentioned earlier are performed on old versions of cookies. The new Cookie category
Is not supported by the javax. servlet. http. Cookie package.

2. Cookie content

The character restrictions of the same cookie content vary with different cookie versions. In cookie version
0, some special characters, such as space, square brackets, Parentheses, equal sign (=), comma, double quotation marks, slash, question mark, @ symbol, colon, the semicolon cannot be used as the cookie content. This is also true.
This is why we set the cookie content to "test_content" in the example.

Although these characters can be used in cookie version 1, the new Cookie specification is not currently supported by all browsers. Therefore, it is safe, we should avoid using these characters in cookie content. (

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.