Cookie读取与写入 Java

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 "";
}

 

你可能感兴趣的:(String,function,object,search,domain,Path)