Detailed description of cookie read/write operations in jsp

Source: Internet
Author: User

Cookie, a session tracking mechanism. Based on the response made by the server accessed by the user, the browser can save a short piece of text information locally to record the user's login username and password. When you log on to the website again next time, the browser searches for local cookies that match the URL Based on the URL entered by the user. If any, the request and the Cookie are sent to the server for processing.

The information in the Cookie is stored as a key-value pair, and the Cookie file is stored in ASCII code. Therefore, if you want to store Chinese information, you need to encode it before storing it in the Cookie, decodes data after reading.

When a Cookie is sent from the server to the client, it is used in the response header information:

Java code

The Code is as follows: Copy code

Set-Cookie: NAME = VALUE;

Expires = DATE;

Path = PATH;

Domain = DOMAIN_NAME;

Secure

NAME = VALUE

Is the most critical attribute in Cookie information. name is the Cookie name and value is the corresponding value. Required.

Expires

Cookie validity period. Format: Wdy, DD-Mon-yyyy hh: MM: ss gmt. If the cookie expires, the cookie becomes invalid. Optional attribute. If no expiration time is specified, it will expire after the current session ends.

Path

The path of the current domain name where the cookie is visible. If it is set to "/", all paths under the current domain can be seen; if it is set to "/news", it can only be visible under "http://XXX.com/news. If this parameter is not set, you can only access the page on which it is generated.

Domain = DOMAIN_NAME

The domain name of the Cookie. The cookie of google.com only belongs to google.com and cannot be operated by baidu.com. When the domain name is set to ".google.com", the first point indicates that all the second-level domain names under google.com share cookies with the first-level domain names. Otherwise, the code.google.com domain name cannot use the cookies under google.com, and only the cookies under code.google.com can be used.

Secure

Specifies whether the current cookie uses the security protocol to send the cookie (SSL, HTTPS, etc ).

The above is the response header settings. If the client needs to submit the Cookie to the server, the format is:

Cookie: NAME1 = OPAQUE_STRING1; NAME2 = OPAQUE_STRING2...

Start with a Cookie. Each key-value pair is separated by a semicolon.

For more information about cookies, see the NetScape Cookie specification. (Currently, most browsers support it. Other Cookie specifications (such as w3c) are not supported by all browsers, so NetScapeCookie is common .)

Java cookies
In java, the Cookie is encapsulated in the javax. servlet. http. Cookie class. Every cookie we operate on is an object of this class.

To add a cookie, declare a Cookie object, that is, javax. servlet. http. cookie objects can contain two parameters (Cookie name and Cookie value) during the Declaration and construction, for example:

The Code is as follows: Copy code

Cookie cookie = new Cookie ("name", "the8m ");

Declares a Cookie object named name and its value is the8m. Next, we need to add the Cookie to the response and send it to the client.

Response. addCookie (cookie );

 

Such a simple Cookie is stored on the client.

Read Cookie

When response. after addCookie adds a Cookie to the client, we can use request. getCookie () is used to obtain an array of Cookie objects because multiple cookies are stored on one page.

The following is an example:

Java code

The Code is as follows: Copy code
<%
If (request. getCookies ()! = Null)
{
For (Cookie coo: request. getCookies ())
{
String name = coo. getName ()
String value = coo. getValue ()
Out. println (name + "--" + value );
}
}
%>

We can also use the built-in hidden object cookie in the EL expression to read data, which is much easier to obtain than using the request object.

Java code

The Code is as follows: Copy code
$ {Cookie} <! -- Display all Cookie objects -->
$ {Cookie. age. name} <! -- Display the name of the Cookie named age -->
$ {Cookie. age. value} <! -- Display the value of Cookie named age -->

Cookie name and Cookie value

The name must comply with RFC 2109. This means that it can only contain ASCII letters and numbers, cannot contain commas, semicolons, or spaces, and cannot start with $. The cookie name cannot be changed after it is created.

The value cannot contain spaces, square brackets, Parentheses, equal signs, commas, double quotation marks, slashes, question marks, @, colons, and semicolons. If the value is binary data, BASE64 encoding is required.

Cookie and Chinese

Cookie files are stored in ASCII encoding format, which occupies 2 bytes, while Chinese characters are Unicode (Unicode contains symbols of all languages in the world, including Chinese characters, 4 characters.

Therefore, if you want to save Chinese Characters in cookies, you must encode them before they can be properly stored and decoded during reading.

Generally, java.net. URLEncoder. encode (String s, String enc) is used for encoding. The application/x-www-form-urlencoded MIME String is obtained.

Use java.net. URLDecoder. decode (String s, String enc) for decoding.

The second parameter in the two methods, usually the default is UTF-8.

Java code

The Code is as follows: Copy code
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" %>
<Jsp: directive. page import = "java.net. *"/>
<%
Cookie cookie = new Cookie (
URLEncoder. encode ("name", "UTF-8 "),
URLEncoder. encode ("Li jialong", "UTF-8 ")
);
Response. addCookie (cookie );
%>
<Html>
<Title> Cookie-Chinese </title>
<Body>
<%
If (request. getCookies ()! = Null)
{
For (Cookie coo: request. getCookies ())
{
String name = URLDecoder. decode (coo. getName (), "UTF-8 ");
String value = URLDecoder. decode (coo. getValue (), "UTF-8 ");
Out. println (name + "--" + value );
}
}
%>
</Body>
</Html>

Application/x-www-form-urlencoded is similar to the percent signs we often see in the browser address bar, for example. Use Google Chrome to search for "name". The last generated URL is:

 

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.