


JS operation cookies include (reading, adding and deleting)_javascript skills
I have always simply used js to implement some cookie operations. Today I have sorted out js's use of cookie operating systems, including: js reading cookies, js adding cookies, and js deleting cookies. Examples are as follows:
< script language="JavaScript" type="text/javascript">
function addCookie(objName,objValue,objHours){//Add cookie
var str = objName "=" escape(objValue);
if(objHours > 0){//When it is 0, the expiration time is not set, and the cookie disappears automatically when the browser is closed
var date = new Date();
var ms = objHours*3600*1000;
date.setTime(date.getTime() ms);
str = "; expires=" date.toGMTString();
}
document.cookie = str;
alert("Add cookie successful");
}
function getCookie(objName){//Get the value of the cookie with 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){//In order to delete the cookie with the specified name, you can set its expiration time to a past time
var date = new Date ();
date.setTime(date.getTime() - 10000);
document.cookie = name "=a; expires=" date.toGMTString();
}
//Read Take out all cookie strings
function allCookie(){//Read all saved cookie strings
var str = document.cookie;
if(str == ""){
str = "No cookies 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("Delete successfully");
}
//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);//expires unit is days
str =";expires=" date.toGMTString();
}
if(path!=""){
str =";path=" path;//Specify the directory where cookies can be accessed
}
if(domain!=""){
str =";domain=" domain;//Specify the domain that can access cookies
}
document.cookie=str;
}
//Get cookies
function getCookie(name){
var str=document.cookie.split(";")
for(var i=0;i
if(str2[0]==name)return unescape(str2[1]);
}
}
//Delete cookie
function delCookie(name){
var date=new Date();
date.setTime(date.getTime()-10000);
document.cookie=name ”=n;expire=” date.toGMTString();
[Personally, I think the following is better! ]
Of course we have to introduce the four attributes of cookies. These attributes are appended to the string value in the following format:
name=
name=
The following is an example. In this example, the cookie "username" is set to expire after 15 minutes, can be accessed by all directories on the server, and can be accessed by all servers in the "mydomain.com" domain. Access, the security status is safe.
// The constructor of Date() is set in milliseconds Unit
// The .getTime() method returns the time in milliseconds
// So to set the 15-minute expiration, multiply 60000 milliseconds by 15 minutes
var expiration = new Date((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 a specific cookie value. [Get the cookie object with the specified name! ]
function getCookie(cookie_name)
{
var allcookies = document.cookie;
var cookie_pos = allcookies.indexOf(cookie_name);
// If the index is found, it means that the cookie exists ,
// Otherwise, it means it does not exist.
if (cookie_pos != -1)
{
// Put cookie_pos at the beginning of the value, just 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 function
var cookie_val = getCookie("username");
3. Why is it useless if I set the cookie expiration time if it is automatically cleared when it is closed?
Let’s study how JSP manipulates cookies?
Cookie concept:
The format of a cookie is actually a piece of plain text information, which is sent by the server to the client along with the web page, and is saved in The specified directory in the client's hard drive. Everyone says that cookies can cause serious security threats, but this is not the case. When the server reads the cookie, it can only read information related to the server. Moreover, the browser Generally, only 300 cookies are allowed to be stored, and each site can store up to 20 cookies. Moreover, the size of each cookie is now 4K, which does not take up much space at all. Moreover, cookies are time-sensitive. For example, if the cookie survival is set If the time is 1 minute, the cookie will be deleted by the browser after one minute
Cookie version:
There are currently two versions :
Version 0: formulated by Netscape. It is also supported by almost all browsers. In order to maintain compatibility, Java currently only supports version 0. There must be no spaces, square brackets, parentheses, equal signs (=), commas, double quotes, or slashes in the cookie content. Question mark, @ symbol, colon, semicolon.
Version 1: Based on the RFC 2109 document. Many restrictions have been relaxed. All the characters restricted above can be used. But in order to maintain compatibility, these special characters should be avoided as much as possible.
Cookie operations in JSP : Type method name Method explanation
String getComment() Returns the comment in the cookie, if there is no comment, it will return a null value.
String getDomain() Returns the domain name applicable to the cookie in the cookie. Use the getDomain() method to indicate browsing The server returns the cookie to other servers in the same domain, and usually the cookie is only returned to the server with the exact same name as the server that sent it. 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 name of the cookie.
String getPath() returns the path to which the cookie applies. If the path is not specified, the cookie will be returned to all pages in the directory where the current page is located and its subdirectories.
boolean getSecure() will return a true value if the browser sends cookies through a secure protocol, and a false value if the browser uses a standard protocol.
String getValue() returns the value of the cookie. The author will also introduce getValue/setValue in detail later.
int getVersion() returns the protocol version that the cookie complies with.
void setComment(String purpose) Sets the comment in the cookie
void setDomain(String pattern) Sets the domain name for the cookie in the cookie
void setMaxAge(int expiry) Sets the cookie expiration time in seconds.
void setPath(String uri) specifies the path for cookies.
void setSecure(boolean flag) Indicates the security protocol used by the browser, such as HTTPS or SSL.
void setValue(String newValue) sets a new value after the cookie is created.
void setVersion(int v) Set the protocol version that the cookie follows
A simple example
1. Write Cookie --- writecookie.jsp
---- -------------------------------------------------- -------
<%@ 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
------------------------------- ----------------------------------
<%
Cookie cookies[]=request.getCookies(); // Read and save all cookies in the applicable directory Into the cookies array
Cookie sCookie=null;
String sname=null;
String name=null;
if(cookies==null) // If there are no cookies
out.print ("none any cookie");
else
{
out.print(cookies.length "
");
for(int i=0;i
sCookie=cookies[i];
sname=sCookie.getName();
name = sCookie.getValue();
out.println(sname "->" name "
");
}
}
%>
Two things to note Questions :
1. Cookie has a problem with the applicable path, that is, if writecookie.jsp and readcookie.jsp are to be placed in the agreed directory, if they are not in the same directory, the path needs to be set when writing, as The path where readcookie.jsp is located.
2. When reading the Cookie array, you need to determine whether it is empty (null). Many codes on the Internet do not write this point.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Many users are increasingly favoring the electronic ecosystem of Xiaomi smart home interconnection in modern life. After connecting to the Mijia APP, you can easily control the connected devices with your mobile phone. However, many users still don’t know how to add Mijia to their homes. app, then this tutorial guide will bring you the specific connection methods and steps, hoping to help everyone in need. 1. After downloading Mijia APP, create or log in to Xiaomi account. 2. Adding method: After the new device is powered on, bring the phone close to the device and turn on the Xiaomi TV. Under normal circumstances, a connection prompt will pop up. Select "OK" to enter the device connection process. If no prompt pops up, you can also add the device manually. The method is: after entering the smart home APP, click the 1st button on the lower left

When buying a computer, we may not necessarily choose a large hard drive. At this time, if we want to add a new hard drive to win11, we can first install the new hard drive we purchased, and then add partitions to the computer. Tutorial on adding a new hard drive in win11: 1. First, we disassemble the host and find the slot of the hard drive. 2. After finding it, we first connect the "data cable", which usually has a fool-proof design. If it cannot be inserted, just reverse the direction. 3. Then insert the new hard drive into the hard drive slot. 4. After inserting, connect the other end of the data cable to the computer's motherboard. 5. After the installation is completed, you can put it back into the host and turn it on. 6. After booting, we right-click "This Computer" and open "Computer Management" 7. After opening, click "Disk Management" in the lower left corner 8. Then on the right you can

How to use pandas to read txt files correctly requires specific code examples. Pandas is a widely used Python data analysis library. It can be used to process a variety of data types, including CSV files, Excel files, SQL databases, etc. At the same time, it can also be used to read text files, such as txt files. However, when reading txt files, we sometimes encounter some problems, such as encoding problems, delimiter problems, etc. This article will introduce how to read txt correctly using pandas

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Practical tips for reading txt files using pandas, specific code examples are required. In data analysis and data processing, txt files are a common data format. Using pandas to read txt files allows for fast and convenient data processing. This article will introduce several practical techniques to help you better use pandas to read txt files, along with specific code examples. Reading txt files with delimiters When using pandas to read txt files with delimiters, you can use read_c

In win11, we can quickly start software or files on the desktop by adding desktop shortcuts, and we only need to right-click the required files to operate. Add a desktop shortcut in win11: 1. Open "This PC" and find the file or software you want to add a desktop shortcut to. 2. After finding it, right-click to select it and click "Show more options" 3. Then select "Send to" - "Desktop Shortcut" 4. After the operation is completed, you can find the shortcut on the desktop.

Example of using OpenCSV to read and write CSV files in Java. CSV (Comma-SeparatedValues) refers to comma-separated values and is a common data storage format. In Java, OpenCSV is a commonly used tool library for reading and writing CSV files. This article will introduce how to use OpenCSV to implement examples of reading and writing CSV files. Introducing the OpenCSV library First, you need to introduce the OpenCSV library to
