Recently in learning some of the implementation details of the servlet, read the source code of the cookie.
A cookie is essentially a session temporary data that the server sends to the client (primarily the browser).
Description of its source code comment document:
Creates a cookie, a small amount of information sent by a servlets to a Web browser, saved by the browser, and later sent B ACK to the server. A cookie ' s value can uniquely identify a client, so cookie is commonly used for session management.
It means that this thing is a lightweight information carrier, sent to the Web browser by the server creation, and then sent back to the server every time the browser sends an HTTP request to the server, letting the server know "This is the user". The "value" of a cookie must be different to uniquely identify a client, so cookies are often used in conjunction with a server-side session.
In the TOMCAT8 source code of the cookie source has nearly 500 lines, many of which are relatively occupied space, such as a series of set,get methods, now take out part of the analysis.
Statement of the Cookie:
1 Public class Implements cloneable, Serializable {2 // code omitted 3 }
Indicates that objects of this class can be copied and persisted.
The static part of a cookie:
1 Private Static Finalcookienamevalidator validation;2 Static {3 Booleanstrictnaming;4String prop = System.getproperty ("Org.apache.tomcat.util.http.ServerCookie.STRICT_NAMING");5 if(Prop! =NULL) {6Strictnaming =Boolean.parseboolean (prop);7}Else {8strictnaming = Boolean.getboolean ("Org.apache.catalina.STRICT_SERVLET_COMPLIANCE");9 }Ten One if(strictnaming) { Avalidation =Newrfc2109validator (); - } - Else { thevalidation =Newnetscapevalidator (); - } - } - + Private Static Final LongSerialversionuid = 1L;
Here is a: Cookienamevalidator object. What does this thing do for me? In fact, validator is a detector that determines whether a value is valid. This means that the object is used to determine if the name of the cookie is valid. So what is the name of a valid cookie? The source document contains instructions:
The name must conform to RFC 2109. That means it can contain only ASCII alphanumeric characters and cannot contain commas, semicolons, or white space or begi N with a $ character. The cookie ' s name cannot is changed after creation.
It's not translated. In short, these rules can be used as the name of a cookie.
The static code block inside the strictnaming is a configuration: In the end is to use Rfc2109validator or netscapevalidator to make the real legal judgment. So what is the difference between these classes? is actually a distinction between the rigor of legal name judgments.
Source code and my comments:
1 classCookienamevalidator {//The base class of the effective judging device, basically do not use this2 Private Static FinalString lstring_file = "Javax.servlet.http.LocalStrings";3 protected Static FinalResourceBundle lstrings =Resourcebundle.getbundle (lstring_file);4 5 protected FinalBitSet allowed;//this thing to achieve the control of the desirable character range, its principle is relatively simple: in a range with a bit to indicate whether it is valid. 6 7 protectedCookienamevalidator (String separators) {//The constructor enters a character set, and the characters in this character set are treated as illegal characters.8allowed =NewBitSet (128);9Allowed.set (0x20, 0x7f); Ten for(inti = 0; I < separators.length (); i++) { One CharCH =Separators.charat (i); A allowed.clear (CH); - } - } the - voidValidate (String name) {//Judging one so whether it's legal - if(Name = =NULL|| Name.length () = = 0) {//The first is to determine whether null or empty string - Throw NewIllegalArgumentException (lstrings.getstring ("Err.cookie_name_blank")); + } - if(!istoken (name)) {//call Istoken to judge. Istoken is responsible for determining whether the name contains illegal characters, and if so, throws an exception. +String errmsg = lstrings.getstring ("Err.cookie_name_is_token"); A Throw Newillegalargumentexception (Messageformat.format (errmsg, name)); at } - } - - Private BooleanIstoken (String possibletoken) {//whether the name is a valid judgment function - intLen =possibletoken.length (); - in for(inti = 0; i < Len; i++) { - Charc =Possibletoken.charat (i); to if(!allowed.get (c)) {//Take each character of the string and make a judgement on the valid character set (Bitset in the above), and if an invalid character is found, the string is invalid . + return false; - } the } * return true; $ }Panax Notoginseng } - the classNetscapevalidatorextendsCookienamevalidator { + //The Netscape specification describes Name=value as A //"A sequence of characters excluding semi-colon, comma and white space" the //We also exclude the ' = ' character that separates NAME from VALUE + Private Static FinalString netscape_separators = ",;" + "=";//equals to take these characters also as illegal characters - $ Netscapevalidator () { $ Super(netscape_separators);//more illegal characters are passed through the construction method of the parent class, making the judgment more rigorous. - } - } the - classRfc6265validatorextendsCookienamevalidator {Wuyi Private Static FinalString rfc2616_separators = "() <>@,;:\ \ \ "/[]?={} \ T";//More illegal characters, more stringent name checks the - Rfc6265validator () { Wu Super(rfc2616_separators); - About //special treatment to allow for Fwd_slash_is_separator property $ BooleanAllowslash; -String prop = System.getproperty ("Org.apache.tomcat.util.http.ServerCookie.FWD_SLASH_IS_SEPARATOR"); - if(Prop! =NULL) { -Allowslash =!Boolean.parseboolean (prop); A}Else { +Allowslash =! Boolean.getboolean ("Org.apache.catalina.STRICT_SERVLET_COMPLIANCE"); the } - if(allowslash) { $Allowed.set ('/'); the } the } the } the - classRfc2109validatorextendsRfc6265validator {//stricter, avoid string starting with $ as the name in Rfc2109validator () { the } the About @Override the voidValidate (String name) { the Super. Validate (name); the if(Name.charat (0) = = ' $ ') { +String errmsg = lstrings.getstring ("Err.cookie_name_is_token"); - Throw Newillegalargumentexception (Messageformat.format (errmsg, name)); the }Bayi } the}
The above source comments basically understand the control of the cookie name is a valid mechanism. This mechanism guarantees the legality of the name of each cookie (and, of course, the specific criteria to be followed).
Then look at the source of the cookie:
1 Private FinalString name;2 PrivateString value;3 4 Private intVersion = 0;// ; Version=1. means RFC 2109 style5 6 //7 //Attributes encoded in the header ' s cookie.8 //9 PrivateString comment;// ; Comment=value. Describes cookie ' s useTen PrivateString domain;//;D Omain=value. Domain that sees Cookie One Private intMaxAge =-1;// ; Max-age=value. Cookies Auto-expire A PrivateString path;// ; Path=value ... URLs that see the cookie - Private BooleanSecure// ; Secure ... e.g. use SSL - Private BooleanHttpOnly;//Not in cookies specs, but supported by browsers
Name and value are the most important two quantities, one is the name of the cookie, one is its value, the name can be duplicated, and the value must be unique. Here is a small detail, the note clearly said that the name can not be changed after creation, then what effect does this final play? Is the effect of blocking changes. Each modification of a string object is a new string whose value is the changed value, then the new object is returned, and the original reference points to the new object instead of actually modifying the object's contents. After finishing it as final, the reference cannot be changed and its value cannot be modified.
The instance variable below is the "attribute" of the cookie. The cookie note also explicitly mentions that many browsers are not very well supported and use caution.
Path: Indicates that the cookie corresponds to a page (usually a directory), the sub-page of the directory can access the cookie, the other is not accessible, if you want to be set to globally accessible, then set to/.
Domain: Specifies the associated Web server domain name.
Secure: Specifies whether the data is transferred securely, either empty or secure, if it is empty with unsecured HTTP, if secure with HTTPS or another encryption method. This is just the encrypted transmission of the content rather than the locally saved cookie.
MaxAge: Maximum life cycle. Integer, in seconds, to set the expiration time for this cookie. If a negative number is disabled, the browser is not saved locally.
Comment: A description of the meaning of this cookie that is displayed by the browser when the cookie is displayed.
The version number used by the Version:cookie. 0 indicates compliance with the cookie specification of Netscape, 1 is the RFC 2109 specification followed by the consortium
The HttpOnly property of the Httponly:cookie. If this property is true, only the information in the HTTP request header will be provided with this cookie, and this cookie cannot be accessed through Document.cookie.
Construction Method:
1 Public Cookie (string name, String value) {2 validation.validate (name); 3 this. Name = name; 4 this. Value = value; 5 }
More straightforward: Check the legitimacy of the name and then inject it.
followed by a whole bunch of get and set methods, all about the attributes of the cookie.
Servlet-cookie Source Code Analysis source environment: TOMCAT8