Cookies
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.
9.3.1 Gets the cookie value of the specified name
This function is part of the Servletutilities.java. Getcookievalue the individual elements of the cookie object array by loop, looking for a cookie with the specified name, or the value of the cookie if found, otherwise, the default value given in the parameter is returned. Getcookievalue can simplify the extraction of cookie value to some extent.
public static String getCookieValue(Cookie[] cookies,
String cookieName,
String defaultValue) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
}
return(defaultValue);
}
9.3.2 automatically saved cookies
The following is the code for the Longlivedcookie class. If you want cookies to be saved automatically when the browser exits, you can replace the standard cookie class with this Longlivedcookie class.
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: Custom Search Engine Interface
Below is also an example of a search engine interface, by modifying the example of the previous HTTP status code. In this servlet, the user interface is dynamically generated rather than provided by static HTML files. In addition to being responsible for reading form data and sending it to search engines, the servlet sends cookies that contain form data to the client. When the customer accesses the same form again, the value of these cookies is used to pre-filled the form so that the form automatically displays the most recently used data.
Searchenginesfrontend.java
The servlet constructs a user interface that is primarily composed of forms. The first time it is displayed, it is similar to the interface provided in the previous static HTML page. However, the value that the user selects will be saved to the cookie (this page sends the data to the Customizedsearchengines Servlet, which sets the cookie). When a user accesses the same page later, the form will automatically fill in the contents of the previous search, even if the browser is exited and then started.
Note that the servlet uses Servletutilities.java, which Getcookievalue described earlier and headwithtitle used to generate part of the HTML page. In addition, we used the Longlivecookie class, which we have described earlier, to create a cookie with a long expiration date.
Package Hall;
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.net.*;
public class Searchenginesfrontend extends HttpServlet {
public void doget (HttpServletRequest request,
HttpServletResponse response)
Throws Servletexception, IOException {
cookie[] cookies = request.getcookies ();
String searchstring =
Servletutilities.getcookievalue (Cookies,
"SearchString",
"Java programming");
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 (title) + Servletutilities.headwithtitle
"<body bgcolor=\" #FDF5E6 \ ">\n" +
"
"\ n" +
"<form action=\"/servlet/hall. Customizedsearchengines\ ">\n" +
"<CENTER> \ n" +
"Search string:\n" +
"<input type=\" text\ "name=\" searchstring\ "\ n" +
"Value=\" "+ searchstring +" \ "> <BR> \ n" +
"Results to show per page:\n" +
"<input type=\" text\ "name=\" numresults\ "\ n" +
"Value=" + numresults + "size=3> <BR> \ n" +
"<input type=\" radio\ "name=\" searchengine\ "\ n" +
"Value=\" google\ "" +
Checked ("Google", SearchEngine) + ">\n" +
"Google |\n" +
"<input type=\" radio\ "name=\" searchengine\ "\ n" +
"Value=\" infoseek\ "" +
Checked ("InfoSeek", SearchEngine) + ">\n" +
"InfoSeek |\n" +
"<input type=\" radio\ "name=\" searchengine\ "\ n" +
"Value=\" lycos\ "" +
Checked ("Lycos", SearchEngine) + ">\n" +
"Lycos |\n" +
"<input type=\" radio\ "name=\" searchengine\ "\ n" +
"Value=\" hotbot\ "" +
Checked ("HotBot", SearchEngine) + ">\n" +
"Hotbot\n" +
"<BR> \ n" +
"<input type=\" submit\ "value=\" search\ ">\n" +
"</CENTER> \ n" +
"</FORM> \ n" +
"\ n" +
"</BODY> \ n" +
"</HTML> \ n");
}
private string checked (string name1, String name2) {
if (Name1.equals (name2))
Return ("CHECKED");
Else
Return ("");
}
}
Customizedsearchengines.java
The previous Searchenginesfrontend servlet sends data to the Customizedsearchengines servlet. This example is similar in many ways to the previous example of HTTP status code, except that this example sends cookies to save user data in addition to constructing a URL for the search engine and sending a redirect response to the user.
Package Hall;
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.net.*;
public class Customizedsearchengines extends HttpServlet {
public void doget (HttpServletRequest request,
HttpServletResponse response)
Throws Servletexception, IOException {
String searchstring = Request.getparameter ("searchstring");
Cookie Searchstringcookie =
New Longlivedcookie ("SearchString", searchstring);
Response.addcookie (Searchstringcookie);
SearchString = Urlencoder.encode (searchstring);
String numresults = Request.getparameter ("Numresults");
Cookie Numresultscookie =
New Longlivedcookie ("Numresults", numresults);
Response.addcookie (Numresultscookie);
String searchengine = Request.getparameter ("SearchEngine");
Cookie Searchenginecookie =
New Longlivedcookie ("SearchEngine", searchengine);
Response.addcookie (Searchenginecookie);
searchspec[] Commonspecs = Searchspec.getcommonspecs ();
for (int i=0; i<commonspecs.length; i++) {
Searchspec searchspec = commonspecs[i];
if (Searchspec.getname (). Equals (SearchEngine)) {
String URL =
Searchspec.makeurl (SearchString, numresults);
Response.sendredirect (URL);
Return
}
}
Response.senderror (response. Sc_not_found,
"No recognized search engine specified.");
}
public void DoPost (HttpServletRequest request,
HttpServletResponse response)
Throws Servletexception, IOException {
Doget (request, response);
}
}