Introduction to JSP servlet Basics: Handling Cookies

Source: Internet
Author: User
Tags constructor header http request send cookies set cookie valid domain

9.1 Cookie Overview

A cookie is a small, plain text message that the server sends to the browser, and the browser sends it to the server as it is when the user accesses the same Web server. By letting the server read the information it originally saved to the client, the site can provide a range of convenience for visitors, such as the identification of users in the online transaction process, the security requirements of the occasion to avoid users repeatedly enter the name and password, the homepage of the portal customization, targeted ads, and so on.

The purpose of cookies is to bring convenience to users and add value to the site. Although there are many misinformation, cookies do not pose a serious security threat. Cookies are never executed in any way, and therefore do not bring viruses or attack your system. In addition, because browsers generally allow only 300 cookies, each site holds up to 20 cookies, and each cookie has a size limit of 4 KB, so cookies won't fill your hard drive and will not be used as a denial of service attack.

Cookie API for 9.2 servlet

To send cookies to the client, the servlet first invokes the new cookie (Name,value) Create one or more cookies (section 2.1) with the appropriate name and value, set various properties (2.2) by cookie.setxxx, and add the cookie to the answer header (2.3) by means of a response.addcookie (cookie).

To read from the client cookie,servlet should call Request.getcookies (), and the GetCookies () method returns an array of Cookie objects. In most cases, you just need to iterate through each element of the array for a cookie with the specified name, and then call the GetValue method on the cookie to get the value associated with the specified name, which is discussed in section 2.4.

9.2.1 Create cookies

You can create cookies by calling the constructor of a cookie object. The constructor for the cookie object has two string parameters: the cookie name and the cookie value. Neither the name nor the value can contain whitespace characters and the following characters:

[ ] ( ) = , " / ? @ : ;

9.2.2 Read and Set cookie properties

Before you add a cookie to the answer header to send, you can view or set the various properties of the cookie. The following summary describes these methods:

Getcomment/setcomment

Gets/sets the comment for the cookie.

Getdomain/setdomain

Gets/sets the domain that the cookie applies to. Generally, cookies are returned only to servers that have exactly the same name as the server that sent it. Use this method to instruct the browser to return cookies to other servers in the same domain. Note the field must start with a point (for example,. sitename.com), and the domain of a non-state class (such as. com,.edu,.gov) must contain two points, and the domain of the country class (such as. com.cn,.edu.uk) must contain three points.

Getmaxage/setmaxage

Gets/sets the time, in seconds, before the cookie expires. If you do not set this value, the cookie is valid only for the current session, which is valid until the user closes the browser, and the cookies are not saved to disk. See the following instructions for Longlivedcookie.

Getname/setname

Gets/sets the name of the cookie. In essence, names and values are the two parts that we always care about. Since the HttpServletRequest GetCookies method returns an array of cookie objects, it is often used to iterate over the array to find a particular name and then check its value with GetValue.

Getpath/setpath

Gets/sets the path that the cookie applies to. If you do not specify a path, the cookie is returned to all pages in the directory and its subdirectories where the current page resides. The method here can be used to set some more general conditions. For example, Somecookie.setpath ("/"), at which point all pages on the server can receive the cookie.

Getsecure/setsecure

Gets/sets a Boolean value that indicates whether the cookie can only be sent over an encrypted connection, that is, SSL.

Getvalue/setvalue

Gets/sets the value of the cookie. As mentioned earlier, names and values are actually two aspects that we always care about. There are exceptions, however, such as the use of the name as a logical token (that is, true if the name exists).

Getversion/setversion

Gets/sets the protocol version that the cookie complies with. Default version 0 (following the original Netscape specification), version 1 compliant with RFC 2109, but not widely supported.

9.2.3 set cookies in the answer header

Cookies can be added to the Set-cookie answer header via the HttpServletResponse Addcookie method. Here is an example:

Cookie userCookie = new Cookie("user", "uid1234");
response.addCookie(userCookie);

9.2.4 read cookies saved to the client

To send cookies to the client, first create a cookie and then send a Set-cookie http reply header with Addcookie. The content is described in section 2.1 above. The HttpServletRequest GetCookies method is invoked when the cookie is read from the client. This method returns an array of cookie objects corresponding to the content in the HTTP request header. After you get this array, you typically iterate through each of the elements, calling GetName to check the names of each cookie until the target cookie is found. The target cookie is then invoked GetValue to perform other processing according to the results obtained.

The above process is often encountered, for the convenience of the meter below we provide a getcookievalue method. As long as the cookie object array, cookie name, and default value are given, the Getcookievalue method returns the cookie value that matches the specified name, and returns the default value if the specified cookie is not found.

9.3 Several cookie tool functions

Here are a few tool functions. These functions, though simple, are useful when dealing with cookies.

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.