欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Cookie扫盲

程序员文章站 2022-05-27 11:05:31
...
1. 如何创建Cookie,JSP是使用如下的语法格式来创建cookie的:

  
Cookie cookie_name =new Cookie("key","value");


eg:

Cookie cookie = new Cookie("name","zhangsan");
cookie.setMaxAge(365*24*60*60); //存活期为1年 ,如果不设置MaxAge,默认关闭浏览器,cookie被清除。负值表示当浏览器关闭时,Cookie将会被删除。零值则是要删除该Cookie。
response.addCookie(cookie);


explain:
JSP是调用Cookie对象相应的构造函数Cookie(name,value)用合适的名字和值来创建Cookie,然后Cookie可以通过HttpServletResponse的addCookie方法加入到Set-Cookie应答头.

取出Cookie:

Cookie[] cookie = request.getCookies();
if(cookie!=null){
for(Cookie c : cookie){
if(c.getName().equals("name")){
out.write(c.getValue()+",cookie maxAge:"+c.getMaxAge());

}
}
}


api:
Object clone()
Overrides the standard java.lang.Object.clone method to return a copy of this cookie.
String getComment()
Returns the comment describing the purpose of this cookie, or null if the cookie has no comment.
String getDomain()
Returns the domain name set for this cookie.
int getMaxAge()
Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.
String getName()
Returns the name of the cookie.
String getPath()
Returns the path on the server to which the browser returns this cookie.
boolean getSecure()
Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol.
String getValue()
Returns the value of the cookie.
int getVersion()
Returns the version of the protocol this cookie complies with.
void setComment(String purpose)
Specifies a comment that describes a cookie's purpose.
void setDomain(String pattern)
Specifies the domain within which this cookie should be presented.
void setMaxAge(int expiry)
Sets the maximum age of the cookie in seconds.
void setPath(String uri)
Specifies a path for the cookie to which the client should return the cookie.
void setSecure(boolean flag)
Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.
void setValue(String newValue)
Assigns a new value to a cookie after the cookie is created.
void setVersion(int v)
Sets the version of the cookie protocol this cookie complies with.