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

Cookie读取与写入 Java

程序员文章站 2024-03-20 14:42:22
...
Cookie读取与写入有两种方法,用程序写和用js写的两种方法,

1 用程序写

例如:

/**
* 根据名称读取cookie
*/
public Object getCookie(String name){
Cookie[] cookie = request.getCookies();
Object object = null;
for(int i=0;i<cookie.length;i++)
{
if(cookie[i].getName().equals(name)==true)
{
object = cookie[i].getValue();
break;
}
}
return object;
}

/**
* @name 设置cookie名称
* @value 设置cookie的值
* @cookieTime 设置cookie的存活时间
* @domain 设置cookie的域名
* @path 设置cookie
*/
public void setCookie(String name,String value,long cookieTime,String domain,String path){
Cookie _cookie = new Cookie(name ,value);
_cookie.setMaxAge(cookieTime);
_cookie.setDomain(domain);
_cookie.setPath(path);
response.addCookie(_cookie);
}

2 用js写:

function fixCookieDate(date) {
var base = new Date(0);
var skew = base.getTime();
if (skew > 0) date.setTime(date.getTime() - skew);
}

function setCookie(name, value, path, domain, secure) {
var expdates = new Date();
fixCookieDate(expdates);
expdates.setTime(expdates.getTime() + (1*60*60*24*1000));
document.cookie = name + "=" + (value) + ((expdates)?"; expires="+expdates.toGMTString():"") + ((path)?"; path="+path:"") + ((domain)?"; domain="+domain:"") + ((secure)?"; secure":"");
}
function getCookie(name) {
var search;

search = name + "="
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length ;
end = document.cookie.indexOf(";", offset) ;
if (end == -1)
end = document.cookie.length;
return document.cookie.substring(offset, end);
}
else
return "";
}


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/xiaoping8411/archive/2009/11/09/4790753.aspx
相关标签: Java .net Blog