9.1 Cookie Overview
Cookies are small plain text information sent by the server to the browser. When a user accesses the same Web server, the browser will send them to the server as they are. By allowing the server to read the information it previously saved to the client, the website can provide a series of convenience for viewers, for example, when a user is identified during an online transaction and has low security requirements, users are not allowed to repeatedly enter their names and passwords, customize the portal's home page, and place advertisements in a targeted manner.
Cookie aims to bring convenience to users and add value to websites. Although there are many false positives, cookies do not actually pose a serious security threat. Cookies will never be executed in any way, so they will not bring viruses or attack your system. In addition, browsers generally only allow 300 cookies, and each site can store up to 20 cookies. The size of each Cookie is limited to 4 KB, So cookies will not fill your hard disk, it will not be used as a "Denial of Service" attack.
9.2 Servlet Cookie API
To send the Cookie to the client, the Servlet first needs to call new Cookie (name, value) to create one or more cookies (Section 2.1) with the appropriate name and value. setXXX sets various attributes (section 2.2) through response. addCookie adds the cookie to the Response Header (section 2.3 ).
To read the Cookie from the client, the Servlet should call the request. getCookies () and getCookies () Methods to return an array of Cookie objects. In most cases, you only need to access each element of the array cyclically to find the Cookie with the specified name, and then call the getValue method for the Cookie to obtain the value associated with the specified name, this part will be discussed in section 2.4.
9.2.1 create a Cookie
You can call the constructor of a Cookie object to create a Cookie. The constructor of a Cookie object has two string parameters: Cookie name and Cookie value. Both names and values cannot contain white spaces and the following characters:
[] () = ,"/? @:;
9.2.2 read and set Cookie attributes
Before adding a Cookie to the response header to be sent, you can view or set various attributes of the Cookie. The following describes these methods:
GetComment/setComment
GET/set Cookie comments.
GetDomain/setDomain
Obtain/set the applicable domain of the Cookie. Generally, a Cookie only returns a server with the same name as the server that sent the Cookie. The method indicates that the browser returns the Cookie to other servers in the same domain. Note that the domain must start with a vertex (for example, .sitename.com), or a non-state domain (such. com ,. edu ,. gov) must contain two vertices, the domain of the Country class (such as .com.cn ,. edu. uk) must contain three vertices.
GetMaxAge/setMaxAge
GET/set the time before the Cookie expires, in seconds. If this value is not set, the Cookie is valid only in the current session, that is, before the user closes the browser, and these cookies are not saved to the disk. See the following LongLivedCookie description.
GetName/setName
Obtain/set the Cookie name. In essence, names and values are two parts that we always care about. Because the getCookies method of HttpServletRequest returns an array of Cookie objects, it is usually used to access this array in a loop to find a specific name, and then use getValue to check its value.
GetPath/setPath
Obtain/set 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. The method can be used to set more general conditions. For example, someCookie. setPath ("/"), all the pages on the server can receive the Cookie.
GetSecure/setSecure
GET/set a boolean value that indicates whether the Cookie can only be sent through an encrypted connection (SSL.
GetValue/setValue
Obtain/set the Cookie value. As mentioned above, the name and value are actually two aspects that we always care about. However, there are some exceptions, such as using the name as a logical tag (that is, if the name exists, it indicates true ).
GetVersion/setVersion
Obtain/set the Protocol version that the Cookie complies. The default version 0 follows the original Netscape specification. Version 1 complies with RFC 2109, but is not widely supported.
9.2.3 set Cookie in response header
Cookie can be added to the Set-Cookie response header Through the addCookie method of HttpServletResponse. The following is an example:
Cookie userCookie = new Cookie ("user", "uid1234 ");
Response. addCookie (userCookie );
9.2.4 read the Cookie stored on the client
To send a Cookie to the client, create a Cookie and then use addCookie to send a Set-Cookie HTTP Response Header. The content has been introduced in section 2.1 above. The getcookie method of HttpServletRequest is called when the client reads the Cookie. This method returns an array of Cookie objects corresponding to the content in the HTTP request header. After this array is obtained, it is generally used to access each element in a loop, call getName to check the names of each Cookie until the target Cookie is found. Call getValue for the target Cookie and perform other Processing Based on the obtained results.
The above process is often encountered. For convenience, we provide a getCookieValue method. If the Cookie object array, Cookie name, and default value are provided, the getCookieValue method returns the Cookie value matching the specified name. If no Cookie is found, the default value is returned.
9.3 Cookie tool Functions
The following are some tool functions. Although these functions are simple, they are useful when dealing with cookies.
9.3.1 obtain the Cookie value of the specified name
This function is part of ServletUtilities. java. GetCookieValue cyclically accesses each element of the Cookie object array to find whether a Cookie with a specified name exists. If so, the Cookie value is returned. Otherwise, the default value is returned. GetCookieValue can simplify the extraction of Cookie values 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 LongLivedCookie code. If you want the Cookie to be automatically saved when the browser exits, you can use this LongLivedCookie class to replace the standard Cookie 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 );
}
}
. Instance: customized search engine Interface
The following is an example of the search engine interface, which is obtained by modifying the previous HTTP status code. In this Servlet, the user interface is dynamically generated rather than provided by static HTML files. In addition to reading form data and sending them to the search engine, Servlet also sends cookies containing form data to the client. When you access the same form again in the future, these Cookie values will be used to pre-fill the form so that the form will automatically display recently used data.
SearchEnginesFrontEnd. java
The Servlet constructs a user interface mainly composed of forms. When it is displayed for the first time, it is similar to the interface provided by the static HTML page. However, the user-selected value will be saved to the Cookie (this page sends data to the CustomizedSearchEngines Servlet, which sets the Cookie ). When you access the same page later, the form automatically fills in the content filled in by the previous search even if the browser is restarted after exiting.
Note that this Servlet uses ServletUtilities. java, where getCookieValue has previously introduced headWithTitle for generating part of the HTML page. In addition, we also use the LongLiveCookie class described above to create a Cookie with a long expiration period.
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 (ServletUtilities. headWithTitle (title) +
"<Body bgcolor = \" # FDF5E6 \ "> \ n" +
"<H1 ALIGN = \" CENTER \ "> Searching the Web </H1> \ 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 to the previous example of HTTP status code in many aspects. The difference is that in this example, apart from constructing a URL for the search engine and sending a redirect response to the user, also, Cookies for storing user data are sent.
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 );
}
}