Cookie操作

一:java

 

创建

Cookie _cookie=new Cookie("user_delfancom", "delfan");
cookie.setMaxAge(30); //秒
response.addCookie(_cookie); //写入客户端硬盘
out.print("写Cookie完成");

 

读取

Cookie cookies[]=request.getCookies(); // 将适用目录下所有Cookie读入并存入cookies数组中
Cookie sCookie=null;
String sname=null;
String name=null;
if(cookies==null){ // 如果没有任何cookie
    out.print("none any cookie");
}else{
    out.print(cookies.length);
    for(int i=0;i<cookies.length;i++){
        sCookie=cookies[i];
        sname=sCookie.getName();
        name = sCookie.getValue();
        out.println(sname + "->" + name);
    }
}

 

删除

 Cookie[] cookies=request.getCookies();
 if(cookies!=null) {   
     for(int i=0;i<cookies.length;i++){
        Cookie cookie = cookies[i];
        if(cookie.getName().equals("spreadN")) {   
            cookies[i].setMaxAge(0);   
            response.addCookie(cookies[i]);   
        }   
     }    
 } 

 

 


二:js的


  js部分:

function SetCookie(name,value)//两个参数,一个是cookie的名子,一个是值
 {
      var Days = 30; //此 cookie 将被保存 30 天
    var exp  = new Date();    //new Date("December 31, 9998");
      exp.setTime(exp.getTime() + Days*24*60*60*1000);
      document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
 }
 function getCookie(name)//取cookies函数        
 {
      var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
      alert(unescape(arr[2]));
      if(arr != null) return unescape(arr[2]); return null;
 
 }
 function delCookie(name)//删除cookie
 {
      var exp = new Date();
      exp.setTime(exp.getTime() - 1);
      var cval=getCookie(name);
      if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
 }

 
  html部分:

 <input type="button" onclick="SetCookie('abc','aaa');" value="set" />
 <input type="button" onclick="getCookie('abc');" value="get" />

 

你可能感兴趣的:(html)