JSP cookie usage

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 cookie information in a directory similar to C: '''''window''' 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.

InJSP, We can also use cookies to write some powerful applications.Program.

Next, I want to introduce how to useJSPCreate and process cookies.

Ii. How to Create a cookie

Import = "javax. servlet. http. Cookie"

After talking so much, you must be curious to knowJSPHow to Create a cookie.JSPUse 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:JSPIt is to call the corresponding constructor cookie (name, value) of the cookie object to create the cookie with the appropriate 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.

InJSP:

type method name stringgetcomment () returns a comment in the cookie. If no comment is provided, a null value is returned. stringgetdomain () 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 vertex (for example, .yesky.com) intgetmaxage () and return the maximum time before the cookie expires, in seconds. Stringgetname () 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. Stringgetpath () returns the applicable Cookie Path. If no path is specified, the cookie will be returned to all the pages in the directory of the current page and Its subdirectories. Booleangetsecure () returns true if the browser sends cookies through the security protocol, and false if the browser uses the standard protocol. Stringgetvalue () returns the cookie value. The author will also introduce getvalue/setvalue in detail later. Intgetversion () returns the Protocol version that the cookie complies. Voidsetcomment (string purpose) sets comments in cookies. Voidsetdomain (string pattern) sets the domain name voidsetmaxage (INT expiry) applicable to cookies in seconds, and sets the cookie expiration time. Voidsetpath (string URI) specifies the path to which the cookie applies. Voidsetsecure (Boolean flag) indicates the security protocol used by the browser, such as https or SSL. Voidsetvalue (string newvalue) Cookie is created and a new value is set. Voidsetversion (INT v) sets 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.JSPThe request. getcookies () method is called 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
<%
// 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

InJSPUse 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 the cookie technology. When a user accesses a webpage, it can create a file on the visitor's machine. We call it a cookie and write a piece of content into it, to identify different users. If the next time the user visits the webpage, the user can read the content in the file again, so that the webpage knows that the user has visited the webpage.

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 writeJSPFile, useJSPOperation cookie.
========================================================

Ii. Save and write the cookie

Actually usedJSPCookie operation is very simple. Let's take a look at the following sectionJSPProgram:

... (Omitted in the middle)

// Save the write 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 section.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 cookie storage duration to 10 seconds on the hard disk of the user's machine. A cookie does not exist on the user's hard disk for an indefinite period of time. When a cookie object is created, we must specify the cookie retention period. After this period is exceeded, cookie files will no longer work and will be deleted by your browser. If we hope that the cookie file will still be valid and can be read from the webpage when users access this page next time, 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 uses a loop statement to traverse the cookie object array just created
Scookie = cookies; // 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 short sectionJSPFiles 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 to retrieve a cookie object in the array, and then we use scookie. getvalue () and scookie. getname () is used 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 thatJSPCookie operations are very simple. 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, called Cookie version 0, was originally developed by Netscape and is supported by almost all browsers. The newer version, Cookie version 1, is developed according to RFC 2109. To ensure compatibility, Java stipulates that all the cookie-related operations mentioned earlier are performed on old versions of cookies. The new Cookie version 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 signs (=), commas, double quotation marks, slashes, question marks, @ symbols, colons, the semicolon cannot be used as the cookie content. 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

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.