什么是Cookie
Cookie是一种在客户端保持HTTP状态信息的技术,它好比商场发放的优惠卡。顾客在一个商场购物结账离开时,商场可以决定是否赠送给顾客一张优惠卡,不同顾客的优惠卡上记载的信息可以不同,例如,记载该顾客累计购物的金额和有效期限。顾客可以决定是否接受这张优惠卡,一旦顾客接受了这张优惠卡,那么他在以后每次光顾该商场时,都将携带这张优惠卡,商场也将根据这张优惠卡上记载的信息进行一些特殊的事务处理,例如,计算折扣率和累加本次购物金额。Cookie是在浏览器访问WEB服务器的某个资源时,由WEB服务器在HTTP响应消息头中附带传送给浏览器的一片数据,WEB服务器传送给各个客户端浏览器的数据是可以各不相同的。浏览器可以决定是否保存这片数据,一旦WEB浏览器保存了这片数据,那么它在以后每次访问该WEB服务器时,都应在HTTP请求头中将这片数据回传给WEB服务器。显然,Cookie最先是由WEB服务器发出的,是否发送Cookie和发送的Cookie的具体内容,完全是由WEB服务器决定的。
WEB服务器通过在HTTP响应消息中增加Set-Cookie响应头字段将Cookie信息发送给浏览器,浏览器则通过在HTTP请求消息中增加Cookie请求头字段将Cookie回传给WEB服务器。一个Cookie只能标识一种信息,它至少含有一个标识该信息的名称(NAME)和设置值(value)。一个WEB站点可以给一个WEB浏览器发送多个Cookie,这样,在WEB浏览器和WEB服务器之间就可以使用多个Cookie来传递多种信息,例如,用一个Cookie来标识访问者的姓名,用另外一个Cookie来标识该用户登录站点的次数。一个Cookie除了有名称和设置值外,它还可以有一些其他的附加属性,例如,Cookie的有效时间。如果设置了Cookie的有效时间,接受它的浏览器进程将该Cookie保存在计算机硬盘中,只有该Cookie超出有效时间后才被删除,这样的Cookie将被同一台计算机上启动的多个浏览器进程共享。正如一个顾客可以有多家商场提供的优惠卡一样,一个WEB浏览器也可以存储多个WEB站点提供的Cookie。为了防止Cookie塞满客户机的硬盘,浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB。如果没有设置Cookie的有效时间,接受它的浏览器进程只将该Cookie保存在自己的内存空间中,在该浏览器进程关闭时,它里面保存的所有Cookie也将随之消失。
Cookie实现了一种在浏览器和服务器之间产生有状态会话的方式,它可以把一个浏览器访问的同一个服务器上的所有程序贯连起来,在这些程序之间传递数据。例如,当用户使用浏览器访问某个网站的登录程序进行登录后,无论这个浏览器再访问该网站的哪个程序,其他程序都能知道访问者的身份信息,这是在WEB站点中非常普遍的一个应用。这种应用通常就是采用Cookie技术来实现的,当WEB服务器程序验证登录请求中的用户名和密码后,产生一个标识该用户身份的标识号,然后在响应消息中将该标识号以Cookie的形式传递给浏览器,浏览器在以后每次访问该WEB服务器时,都自动在请求消息头中将标识号又以Cookie的形式返回给WEB服务器,凭借浏览器返回的标识号,WEB服务器的其他程序就能分辨出当前请求是由哪个用户发出的。但是,有一点要注意,不保存在硬盘中的Cookie信息是否可以被同一台计算机上启动的多个浏览器进程共享,不同的浏览器有不同的处理方式。对于IE浏览器来说,保存在其中一个浏览器进程的内存空间中的Cookie是不能被其他浏览器进程共享的,这就会出现同一台计算机上的每个浏览器进程都会与服务器形成各自独立的会话;而对于Mozilla Firefox浏览器来说,所有的进程和标签页都共享cookie信息。另外,在IE浏览器中按Ctrl-N键(或者单击“文件”?;;“新建”?;;“窗口”菜单)打开的窗口或者是用javascript的window.open语句打开的窗口,都会共享原窗口的Cookie信息,因为它们属于同一个浏览器进程内部的多个窗口(出自张孝祥老师的<深入体验JavaWeb开发内幕>手稿很期待这本书的面世)
///
我们学习了可以用jsp Cookie类来创建cookie,当然其它语言也可以创建包括客户端脚本语言javascript,vbscript同在我们主要谈谈用javascript,和html来创建cookie
1 Creating a Cookie that Is Valid Until a Certain Date
<HTML>
<HEAD>
<TITLE>Creating a cookie that is valid until a certain date</TITLE> <META
HTTP-EQUIV="Set-Cookie" CONTENT="userId=678;expires=Wednesday, 26-Dec-01 16:00:00 GMT;
path=/">
</HEAD>
<BODY>
Unless you set your browser to not accept cookies, a cookie called userId with a value of
678 has been created for you.
</BODY>
</HTML>
/////
2 Creating Cookies with document.cookiess
document.cookiess = "cookieName=cookievalue
[; expires=timeInGMTString]
[; path=pathName]
[; domain=domainName]
[; secure]"
Listing 25.3 Creating a Cookie with document.cookiess
<HTML>
<HEAD>
<TITLE>Creating a cookie with document.cookiess</TITLE>
<SCRIPT LANGUAGE="javascript">
document.cookiess="Quantity=7";
</SCRIPT>
</HEAD>
<BODY>
This page creates a cookie on the client side.
Make sure that your browser is set to accept cookies.
</BODY>
</HTML>
Creating Cookies with the setCookie Function
For example, you'll want to create a cookie when your user chooses to buy something in your online store web application
Listing 25.4 The setCookie Function
<SCRIPT LANGUAGE="javascript">
function setCookie(name, value, expires, path, domain, secure) {
document.cookiess = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
</SCRIPT>
Listing 25.7 An Example that Creates a Cookie with an Expiration Date
<HTML>
<HEAD>
<TITLE>Using the setCookie function</TITLE>
<SCRIPT LANGUAGE="javascript">
function setCookie(name, value, expires, path, domain, secure) {
document.cookiess = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function fixDate(date) {
var base = new Date(0);
var skew = base.getTime();
if (skew > 0) date.setTime(date.getTime() - skew);
}
var expiryDate = new Date();
fixDate(expiryDate);
expiryDate.setTime(expiryDate.getTime() + 365 * 24 * 60 * 60 * 1000);
setCookie("authorizationLevel", 2, expiryDate);
</SCRIPT>
</HEAD>
<BODY>
A cookie which is valid for a year has been created for this page.
</BODY>
</HTML>
Listing 25.9 Writing and Reading Cookies
<HTML>
<HEAD>
<TITLE>Writing and Reading Cookies</TITLE>
<SCRIPT LANGUAGE="javascript">
function setCookie(name, value, expires, path, domain, secure) {
document.cookiess = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie(name) {
var cName = name + "=";
var dc = document.cookiess;
if (dc.length>0) {
begin = dc.indexOf(cName);
if (begin != -1) {
begin += cName.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin,end));
}
}
return null;
}
</SCRIPT>
</HEAD>
<BODY>
Type in your user id, and then click the Create Cookie button.
A cookie will be created for you.
<BR>
<FORM>
User ID: <INPUT TYPE=TEXT NAME=UserID>
<BR>
<INPUT TYPE=BUTTON value="Create Cookie"
onClick='setCookie("UserID", document.FORMs[0].UserID.value)'>
<BR>
Click the Read Cookie button to display the cookie.
<INPUT TYPE=BUTTON value="Read Cookie"
onClick='alert(getCookie("UserID"))'>
</FORM>
</BODY>
</HTML>
Listing 25.10 Deleting a Cookie
<SCRIPT LANGUAGE="javascript">
function deleteCookie (name, path, domain) {
if (getCookie(name)) {
document.cookiess = name + "=" +
((path==null) ? "" : "; path=" + path) +
((domain==null) ? "" : "; domain=" + domain) +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
function getCookie(name) {
var cName = name + "=";
var dc = document.cookiess;
if (dc.length>0) {
begin = dc.indexOf(cName);
if (begin != -1) {
begin += cName.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin,end));
}
}
return null;
}
</SCRIPT>
Checking If the Browser Can Accept Cookies Using javascript
用javascript来检查用户浏览器是否支持cookie技术
Listing 25.11 Checking If the Browser Can Accept Cookies Using javascript
<HTML>
<HEAD>
<SCRIPT LANGUAGE="javascript">
document.cookiess="test=OK";
function getCookie(name) {
var cName = name + "=";
var dc = document.cookiess;
if (dc.length>0) {
begin = dc.indexOf(cName);
if (begin != -1) {
begin += cName.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin,end));
}
}
return null;
}
if (getCookie('test')==null)
alert("Please change your browser to accept cookies.");
else
alert("Browser accepts cookies");
</SCRIPT>
</HEAD>
<BODY>
The page content
</BODY>
</HTML>
Checking If the Browser Accepts Cookies Without javascript
不用javascript来检查用户浏览器是否支持cookie技术!!!
Another way to check if the browser is willing to accept cookies is by creating a cookie on one page and then immediately redirecting the user to a second page. In the second page you can then try to read the cookies. The code in Listing 25.12 uses the <META> tag to create a cookie called "test" and then redirects the browser to a second page called checkCookie.jsp (in Listing 25.13).
Listing 25.12 Checking Browser Cookie Acceptance with Redirection
<HTML>
<HEAD>
<META HTTP-EQUIV="Set-Cookie" CONTENT="test=ok;">
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=checkCookie.jsp">
</HEAD>
</HTML>
In the second page, implemented using ASP in this example, you try to read the same cookie using the code in Listing 25.13.
Listing 25.13 Reading the Cookies in the Browser Cookie Acceptance Test
<%
If Request.cookiesss("test") <> "" Then
Response.Write "Cookies accepted."
Else
Response.Write "Cookies not accepted."
End If
%>
Even though the code in this example only sends a message to the user telling him or her whether or not his or her browser accepts cookies, you can modify it to suit your needs. For instance, you can transfer the user to a warning page if the cookies are not accepted.
了解一个cookie文件里面的内容的含义!!!!!!!
3.5 What are all those entries in my cookies.txt file?
The layout of Netscape's cookies.txt file is such that each line contains one name-value pair. An example cookies.txt file may have an entry that looks like this:
.netscape.com TRUE / FALSE 946684799 NETSCAPE_ID 100103
Each line represents a single piece of stored inFORMation. A tab is inserted between each of the fields.
From left-to-right, here is what each field represents:
domain - The domain that created AND that can read the variable.
flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.
path - The path within the domain that the variable is valid for.
secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.
name - The name of the variable.
value - The value of the variable.
好现在还看看其它方面的,有趣的一面!
在window当中cookie一般存放在C:/Documents and Settings/wwwfox/Cookies
wwwfox为我登录xp的账号,当然由于ie版本不同存放的位置也有所不同,你可以到微软官方网站上去查看,当然最好的方法就是搜一下Cookie文件就可以知道具体在存放在那里了,
下面是Cookies下面的一个Cookie文件[email protected]内容是:
advpost
0
219.239.245.203/cgi-bin/
1536
1276665728
29789832
2326352352
29783688
对应方法
advpost--->cookie.getName
0--->cookie.getvalue()
1536-->cookie.getMaxAge()如返回为-1表示关闭浏览器cookie就失效
后面就是创建日期,失效日期
创建时间,失效时间
现在教你怎么用jsp编程查看上网时网站给你创建的cookie文件,
问题一.cookiess只能由它创建的网站访问,那么我们怎么能够在自己的电脑是运行自己的服务器查看出来呢,如果能成那就是cookie欺骗。侵入别人网站的根源。
好通过示例来演示:, wwwfox@csdn[2].txt当然它的命名是
你的用户电脑帐号@产生的COOKIE的网页文件所在的WEB目录[COOKIE改变的次数].txt
wwwfox电脑帐号在访问csdn网站时是不会发送到csdn网站上去的,也就是只能在我的电脑wwwfox帐号上使用这个cookie其人(帐号)是不能用的。。
在C:/Documents and Settings/wwwfox/Cookies下我有一个登录csdn网站时由它创建的cookie
wwwfox@csdn[2].txt的内容是:
ABCDEF
hbWhkUhCWfRTUyeAVO5k79qTBFZXtGV2qfwAROv%252fvVk9qF3rfkcZQbl1IdMsBxhy15Y%252fqwN2XiLyTy%252fDGuW4LY7zZll16huuVbnJ0CEun26I%252f2bynXLPd2Ymq%252bn2Mt11pSP5w3%252fZNXt9ZJEp79VMCw%253d%253d
csdn.net/
1536
3743055744
29786511
2555961280
29783695
////////////////////////////
在C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/test新建一个文件checkCookie.jsp
<%@page pageEncoding="gb2312" %>
<%
Cookie[] cookie=request.getCookies();
out.println("this is www.csdn.net/<br>");
out.println("<br>");
for(int i=0;i<cookie.length;i++)
{
if(cookie.getName().equals("ABCDEF"))
{
String name=cookie.getName();
String value=cookie.getvalue();
int maxage=cookie.getMaxAge();
out.println("name="+cookie.getName()+"<br>");
out.println("value="+cookie.getvalue()+"<br>");
out.println("maxage="+cookie.getMaxAge()+"<br>");
//out.println("setMaxAge为30");
//cookie.setMaxAge(30);
//out.println("之后为maxage="+cookie.getMaxAge()+"<br>");
out.println("domain="+cookie.getDomain()+"<br>");
out.println("secure="+cookie.getSecure()+"<br>");
out.println("path="+cookie.getPath()+"<br>");
}
}
%>
好现在访问一下
http://localhost:8080/test/checkCookie.jsp是不是显示:
this is www.csdn.net
而没有取到值:因为只能在它的domain下能访问到这个cookie
好现在我们来
把C:/WINDOWS/SYSTEM32/DRIVERS/etc下面的hosts.sam打开修改其中的
127.0.0.1 hostname
为127.0.0.1 www.csdn.net
在这里你还可以再添加多行和上面相访的键值对,这个比外网的dsn优先级高所以它先把www.csdn.net解释成本地的127.0.0.1所以你就可以由这个访问了,这也可以解释为什么我们可以在ie敲http://localhsot的原因,这里localhost你可随便改成你喜欢的名称.
保存
修改conf/servlet.xml当中的端口为80端口
<Connector port="80" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" />
好现在启动tomcat访问http://www.csdn.net/test/checkCookie.jsp
得到结果啦:
this is www.csdn.net
name=ABCDEF
value=hbWhkUhCWfRTUyeAVO5k79qTBFZXtGV2qfwAROv%252fvVk9qF3rfkcZQbl1IdMsBxhy15Y%252fqwN2XiLyTy%252fDGuW4LY7zZll16huuVbnJ0CEun26I%252f2bynXLPd2Ymq%252bn2Mt11pSP5w3%252fZNXt9ZJEp79VMCw%253d%253d
maxage=-1
domain=null
secure=false#一般为默认值false不然为true就表示在像ssl验证时才能访问些cookie
path=null
由于在本机不能创建cookie所以不能演示修改cookie值给大家看,这就是欺骗哟!
达内的论坛cookie
存放用户名和密码没有经过加密的如
amembernamecookie
javazhai#这里是我的用户名
219.239.245.203/cgi-bin/
1536
2476861952
29789838
3517958576
29783694
*
apasswordcookies
xxxxxx#这里是我的密码
219.239.245.203/cgi-bin/
1536
2476861952
29789838
3517958576
29783694
而csdn是经过加密方式存储的如
ABCDEF
hbWhkUhCWfRTUyeAVO5k79qTBFZXtGV2qfwAROv%252fvVk9qF3rfkcZQbl1IdMsBxhy15Y%252fqwN2XiLyTy%252fDGuW4LY7zZll16huuVbnJ0CEun26I%252f2bynXLPd2Ymq%252bn2Mt11pSP5w3%252fZNXt9ZJEp79VMCw%253d%253d