9.1Cookie Overview
Cookie is a small amount of plain text information sent by the server to the browser. When the user enters the same web server, the browser sends them to the server. By letting the server reads the information you originally saved to the client, the website can provide the viewer to provide a series of convenience, such as the user identity in the online transaction process, and the security requirements are not high to avoid user repeated input name and password, portal The home page is customized, targetedly putting advertisements, and so on.
The purpose of cookie is to bring convenience to users, bring value to the website. Although there are many mistakes, in fact, cookies will not cause serious security threats. Cookie will never be executed in any way, so there will be no virus or attack your system. In addition, since the browser is generally only allowed to store 300 cookies, each site stores up to 20 cookies, each cookie size is limited to 4 KB, so the cookie will not be full of your hard drive, and it will not be used as "refusal." Service "attack means.
9.2 Servlet's cookie API
To send cookies to the client, servlet To create one or more cookies (2.1 sections) with the appropriate name and value, set various properties (2.2) through cookie.setxxx, pass Response.addcookie (cookie) Add cookies to your response head (Section 2.3).
To read from the client, servlet should call the request.getCookies (), and the getCookies () method returns an array of cookie objects. In most cases, you only need to use the individual elements of the array to find the cookie of the array, and then call the getValue method to get the value associated with the specified name, this part of this session will be discussed in Section 2.4.
9.2.1 Creating a cookie
Call the constructor of the cookie object to create a cookie. The constructor of the cookie object has two string parameters: cookie name and cookie value. Names and values cannot contain blank characters and the following characters:
[] () =, "/? @:;
9.2.2 Reading and setting the cookie properties
Before adding cookies, you can view or set up a variety of properties for cookies. These methods are described in the following summary:
Getcomment / setcomment
Get / set the annotation of cookies.
GetDomain / setdomain
Get / set the field for cookies. Generally, cookies only returns the same server that is identical to the server name transmitted. Using the method here, you can indicate that the browser returns the cookie to other servers in the same domain. Note that the domain must start with a point (for example, .sitename.com), non-national domain (such as .com, .edu, .gra) must contain two points, national domains (such as .com.cn, .edu. UK) must contain three points.
GetMaxage / SetMaxage
Get / set the time before the cookie expires, in seconds. If this value is not set, the cookie is only valid within the current session, that is, valid before the user closes the browser, and these cookies are not saved on the disk. See below with the instructions on LongliveDCookie.
GetName / SetName
Get / set the name of the cookie. Essentially, the names and values are two parts we have always cared. Since the GetCookies method of HTTPSERVLETREQUEST returns a Cookie object array, therefore usually uses a loop to access this array to find a specific name, and then check its value with getValue. getPath / setPath
Get / set the path to the cookie. If the path is not specified, the cookie will return to all the pages in the current page where the current page is located and its subdirectory. The method here can be used to set some more general conditions. For example, someCookie.SetPath ("/"), at which time all pages on the server can receive the cookie.
GetSecure / SetSecure
Get / set a boolean value that represents whether cookies can only be sent by encrypted connections (ie, SSL).
GetValue / SetValue
Get / set the value of the cookie. As mentioned earlier, the names and values are actually two aspects we have always cared. However, there are also some exceptions, such as using the name as a logical tag (that is, if the name exists, it means true.
Getversion / setVersion
Get / set the version of the protocol complied with Cookies. The default version 0 (complies with the original Netscape specification); version 1 follows RFC 2109, but has not been widely supported.
9.2.3 Set cookies in your response
Cookies can join the set-cookie response head with the AddCookie method of HTTPSERVLETRESPONSE. Below is an example:
Cookie UserCookie = New Cookie ("User", "UID1234);
Response.addcookie (UserCookie);
9.2.4 Read Save to Client Cookies
To send cookies to the client, first create a cookie, then send a set-cookie HTTP response head with AddCookie. These contents have been described above in Top 2.1. The getCookies method that calls HTTPSERVLETREQUEST when reading cookies from the client. This method returns an array of cookie objects corresponding to content in the HTTP request header. After getting this array, it is generally used to access the individual elements in the loop, call GetName to check the names of each cookie until the target cookie is found. Then, the GetValue is then called to this target cookie, and other processing is performed according to the result.
The above processing process often encounters, and provides a getCookieValue method for the convenience meter. Just give the cookie object array, the cookie name, and defaults, the getCookieValue method returns a cookie value that matches the specified name. If you can't find the specified cookie, return the default value.
9.3 Several cookie tool functions
Here is a few tool functions. Although these functions are simple, it is useful when dealing with cookies.
9.3.1 Get the cookie value of the specified name
This function is part of ServletUtilities.java. GetCookieValue sequentially accesses the various elements of the cookie object array via a loop, finds a cookie for specifying the name, if you find it, return the value of the cookie; otherwise, return the default value given in the parameter. GetCookieValue can simplify the extraction of the cookie value to a certain extent.
Public Static String getCookieValue (cookie [] cookies,
String cookiename,
String defaultValue) {
For (int i = 0; i IF (cookiename.equals (cookie.getname ()))) Return (cookie.getValue ()); } Return (DefaultValue); } 9.3.2 Automatically saved cookies Below is the code of the LONGLIVEDCOOKIE class. If you want the cookie to save automatically when the browser exits, you can use this LONGLIVEDCOOKIE class to replace standard Cookie classes. Package Hall; Import javax.servlet.http. *; Public class longlivedcookie extends cookie { Public static final int seconds_per_year = 60 * 60 * 24 * 365; Public longlivedcookie (string name, string value) { Super (Name, Value); SetMaxage (Seconds_Per_Year); } } 9.4. Example: Customized Search Engine Interface The following is also an example of a search engine interface, by modifying an example of the front HTTP status code. In this servlet, the user interface is dynamically generated instead of being provided by a static HTML file. In addition to reading form data and sending them to search engines, servlet is sent to the client. When the customer has access to the same form again, these cookies will be used to pre-fill the form, so that the form automatically displays the most recently used data. Searchenginesfrontend.java This servlet constructs a user interface that is mainly composed of a form. When the first display, it is similar to the interface provided by the static HTML page. However, the value selected by the user will be saved to the cookie (this page sends the data to the CustomizeDsearchengines Servlet, which is set by the latter). When the user enters the same page in the future, even if the browser is started, the content is automatically filled in the previous search. Note that servlet uses servletutilities.java, where getCookieValue has been introduced, and HeadwithTitle is used to generate a part of the HTML page. In addition, here also used the LongliveCookie class that has been described above, and we use it to create a Cookie for a long waste term. Package Hall; Import java.io. *; Import javax.servlet. *; Import javax.servlet.http. *; Import java.net. *; Public class seat searchenginesfrontend extends httpservlet { Public void doget (httpservletRequest Request, Httpservletresponse response Throws servletexception, ioException { Cookie [] cookies = Request.getCookies (); String searchString = ServletUtilities.getCookieValue (cookies, "searchstring", "Java programing"); String NumResults = ServletUtilities.getCookieValue (cookies, "NumResults", "10"); String searchengine = ServletUtilities.getCookieValue (cookies, "Searchengine", "google"); Response.setContentType (Text / HTML "); PrintWriter out = response.getwriter (); String title = "searching the web"; Out.println (servletutilities.headwithtitle (title) "
"
"\N"
"