All these operations are simple to implement cookies in js. Today, I sorted out the cookie operating system in js, including reading cookies in js, adding cookies in js, and deleting cookies in js, example:
Copy codeThe Code is as follows:
<! Doctype html public "-// W3C // dtd html 4.01 // EN" "http://www.w3.org/TR/html4/strict.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = GB2312"/>
<Title> cookie processing function exercise (I wrote it, not what I think: Improving object-oriented) </title>
<Script language = "JavaScript" type = "text/javascript">
Function addCookie (objName, objValue, objHours) {// Add cookie
Var str = objName + "=" + escape (objValue );
If (objHours> 0) {// when the value is 0, no expiration time is set. When the browser is disabled, the cookie disappears automatically.
Var date = new Date ();
Var MS = objHours x 3600*1000;
Date. setTime (date. getTime () + MS );
Str + = "; expires =" + date. toGMTString ();
}
Document. cookie = str;
Alert ("cookie added successfully ");
}
Function getCookie (objName) {// obtain the cookie value of the specified name
Var arrStr = document. cookie. split (";");
For (var I = 0; I <arrStr. length; I ++ ){
Var temp = arrStr [I]. split ("= ");
If (temp [0] = objName) return unescape (temp [1]);
}
}
Function delCookie (name) {// to delete a cookie with the specified name, you can set its expiration time to a previous time.
Var date = new Date ();
Date. setTime (date. getTime ()-10000 );
Document. cookie = name + "= a; expires =" + date. toGMTString ();
}
// Read all cookie tokens
Function allCookie () {// read all saved cookie strings
Var str = document. cookie;
If (str = ""){
Str = "No cookie is saved ";
}
Alert (str );
}
Function $ (m, n ){
Return document. forms [m]. elements [n]. value;
}
Function add _(){
Var cookie_name = $ ("myform", "cookie_name ");
Var cookie_value = $ ("myform", "cookie_value ");
Var cookie_expireHours = $ ("myform", "cookie_expiresHours ");
AddCookie (cookie_name, cookie_value, cookie_expireHours );
}
Function get _(){
Var cookie_name = $ ("myform", "cookie_name ");
Var cookie_value = getCookie (cookie_name );
Alert (cookie_value );
}
Function del _(){
Var cookie_name = $ ("myform", "cookie_name ");
DelCookie (cookie_name );
Alert ("deleted successfully ");
}
</Script>
// Add cookie
Function addCookie (name, value, expires, path, domain ){
Var str = name + "=" + escape (value );
If (expires! = ""){
Var date = new Date ();
Date. setTime (date. getTime () + expires * 24*3600*1000); // The unit of expires is day.
Str + = "; expires =" + date. toGMTString ();
}
If (path! = ""){
Str + = "; path =" + path; // specify the directory where the cookie can be accessed
}
If (domain! = ""){
Str + = "; domain =" + domain; // specify the cookie-accessible domain
}
Document. cookie = str;
}
// Obtain the cookie
Function getCookie (name ){
Var str = document. cookie. split (";")
For (var I = 0; I <str. length; I ++ ){
Var str2 = str [I]. split ("= ");
If (str2 [0] = name) return unescape (str2 [1]);
}
}
// Delete the cookie
Function delCookie (name ){
Var date = new Date ();
Date. setTime (date. getTime ()-10000 );
Document. cookie = name + "= n; expire =" + date. toGMTString ();
[I personally think this is better.]
Of course, we also need to introduce the four attributes of cookies. These attributes are added to the string value in the following format:
Name = <value> [; expires = <date>] [; domain = <domain>] [; path = <path>] [; secure]
Name = <value> [; expires = <date>] [; domain = <domain>] [; path = <path>] [; security]
<Value>, <date>, <domain>, and <path> should be replaced with the corresponding values. <Date> The GMT format should be used. You can use the. toGMTString () method of the Date type date in the Javascript script language to obtain the Date value in the GMT format. Square brackets indicate that this item is optional. For example, square brackets on the two sides of [; secure] indicate that "; secure" must be added after the cookie string value to set the cookie to secure. If "; secure" is not added to the cookie string, the cookie is insecure. Do not add the angle brackets <> and angle brackets [] to the cookie (unless they are the content of some values ). You can set attributes in any order.
In this example, the cookie "username" is set to expire after 15 minutes and can be accessed by all directories on the server, it can be accessed by all servers in the "mydomain.com" domain. The security status is secure.
Copy codeThe Code is as follows:
// Date () constructor is set in milliseconds
//. GetTime () method return time, in milliseconds
// Set the expiration time to 15 minutes. The expiration time must be 60000 milliseconds and 15 minutes.
Var expiration = new Date (). getTime () + 15*60000 );
Document. cookie = "username =" + escape (form. username. value) + "; expires ="
+ Expiration. toGMTString () + "; path =" + "/" + ";_
Domain = "+" mydomain.com "+"; secure ";
// We define a function to read specific cookie values. [Get the cookie object with the specified name!]
Function getCookie (cookie_name)
{
Var allcookies = document. cookie;
Var cookie_pos = allcookies. indexOf (cookie_name );
// If an index is found, the cookie exists,
// Otherwise, it indicates that it does not exist.
If (cookie_pos! =-1)
{
// Put cookie_pos at the beginning of the value. You only need to add 1 to the value.
Cookie_pos + = cookie_name.length + 1;
Var cookie_end = allcookies. indexOf (";", cookie_pos );
If (cookie_end =-1)
{
Cookie_end = allcookies. length;
}
Var value = unescape (allcookies. substring (cookie_pos, cookie_end ));
}
Return value;
}
// Call a function
Var cookie_val = getCookie ("username ");
3. Why is it useless if I set the cookie expiration time to automatically clear it when it is disabled?
To study how JSPs manipulate cookies?
Cookie Concept:
The Cookie format is actually a piece of plain text information, which is sent by the server along with the webpage to the client and saved in the specified directory on the client's hard disk. it is said that cookies may cause serious security threats. when the server reads the Cookie, it can only read the server-related information. in addition, browsers generally only allow 300 cookies, and each site can store up to 20 cookies. The size of each Cookie is currently 4 K, which does not occupy much space. moreover, cookies are time-effective. for example, if the Cookie survival time is set to 1 minute, the Cookie will be deleted by the browser one minute later.
Cookie version:
There are currently two versions:
Version 0: Developed by Netscape and supported by almost all browsers. in Java, to maintain compatibility, only version 0 is supported currently. The Cookie content cannot contain spaces, square brackets, Parentheses, equals signs (=), commas, double quotation marks, slashes, question marks, @ symbol, colon, semicolon.
Version 1: According to RFC 2109, many restrictions are relaxed. The characters above can be used. To maintain compatibility, avoid using these special characters.
Cookie operations in JSP: Type method name method explanation
String getComment () returns the comments in the cookie. If there is no comments, a null value is returned.
String getDomain () returns the domain name applicable to the cookie in the Cookie. the getDomain () method can be used to instruct the browser to return the Cookie to other servers in the same domain. Generally, the Cookie only returns the server with the same name as the server that sent the Cookie. Note that the domain name must start with a dot
Int getMaxAge () returns the maximum time before the Cookie expires, in seconds.
String getName () returns the Cookie name.
String getPath () returns 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.
Boolean getSecure (): If the browser sends cookies through the security protocol, the return value is true. If the browser uses the standard protocol, the return value is false.
String getValue () returns the Cookie value. The author will also introduce getValue/setValue in detail later.
Int getVersion () returns the Protocol version that the Cookie complies.
Void setComment (String purpose) set comments in cookie
Void setDomain (String pattern): Set the domain name applicable to cookies.
Void setMaxAge (int expiry) is calculated in seconds to set the Cookie expiration time.
Void setPath (String uri) specifies the path to which the Cookie applies.
Void setSecure (boolean flag) indicates the security protocol used by the browser, such as HTTPS or SSL.
Void setValue (String newValue) cookie is created and a new value is set.
Void setVersion (int v) sets the Protocol version that Cookie complies.
A simple example
1. Write Cookie --- writecookie. jsp
-------------------------------------------------------------
Copy codeThe Code is as follows:
<% @ Page contentType = "text/html; charset = ISO8859_1" %>
<%
Cookie _ cookie = new Cookie ("user_delfancom", "delfan ");
_ Cookie. setMaxAge (30*60); // set the Cookie survival time to 30 minutes.
Response. addCookie (_ cookie); // write to the client Hard Disk
Out. print ("Cookie writing completed ");
%>
2. Read Cookie. jsp --- readcookie. jsp
-------------------------------------------------------------
Copy codeThe Code is as follows:
<%
Cookie cookies [] = request. getCookies (); // read all cookies in the applicable directory and store them in the cookies Array
Cookie sCookie = null;
String sname = null;
String name = null;
If (cookies = null) // if no cookie exists
Out. print ("none any cookie ");
Else
{
Out. print (cookies. length + "<br> ");
For (int I = 0; I <cookies. length; I ++) // list all available cookies cyclically.
{
SCookie = cookies [I];
Sname = sCookie. getName ();
Name = sCookie. getValue ();
Out. println (sname + "->" + name + "<br> ");
}
}
%>
Two issues that need attention:
1. cookie has a problem with the applicable path, that is, if writecookie. jsp and readcookie. jsp should be placed in the consent directory. If not in the same directory, you must set the path to readcookie when writing. the path of the jsp.
2. When reading the Cookie array, You need to determine whether it is null. This is not written in many code on the Internet.