-- Cookie usage in JSP!
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 stores 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 () returns the comments in the cookie. If there is no comments, 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 sends 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 () 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.
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 () returns the cookie value. The author will also introduce getvalue/setvalue in detail later.
Int getversion () returns the Protocol version that the cookie complies.
Void setcomment (string purpose) sets the comments in the cookie.
Void setdomain (string pattern): Set the domain name applicable to cookies.
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.
Void setvalue (string newvalue) Cookie is created and a new value is set.
Void setversion (INT v) sets the Protocol version that 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 the username from the submitted HTML form.
Cookie theusername = new cookie ("username", username); // create a cookie with "username", username value/pair
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 );
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 use JSP to operate cookies when writing JSP files.
Ii. Write cookie
In fact, using JSP to operate cookies is very simple. Let's look at the following JSP program:
... (Omitted in the middle)
<%
String cookiename = "sender ";
Cookie = new cookie (cookiename, "test_content ");
Cookie. setmaxage (10 );
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 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 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 ();
Cookie scookie = NULL;
String svalue = NULL;
String sname = NULL;
For (INT I = 0; I {
Scookie = Cookies [I];
Svalue = scookie. getvalue ();
Sname = scookie. getname ();
%>
<%
}
%>
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 circular statement to traverse the cookie object array we just created. We use scookie = Cookies [I] 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 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, 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. (Karry/Public Network News)