Cookie、cookie使用方法、保存用戶名密碼
//設置Cookie, //cname 獲取時所需參數 //username,password 用於記住賬號密碼,如果只要存一個參數 password為空即可 //exdays 設置過期參數 設為負數即可刪除(如-1) function setCookie(cname,username,password,exdays){ let val=""; if(username&&password){ val=username+"#"+password; }else if(username&&!password){ val=username; } var d = new Date(); d.setTime(d.getTime()+(exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname+"="+val+"; "+expires+"; path=/"; } //根據名稱獲取 //如果設置的為兩個參數、則會以數組的方式返回例如 a[0]獲取第一個 function getCookie(cname){ var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i].trim(); if (c.indexOf(name)==0) { let val= c.substring(name.length,c.length); if(val.indexOf("#")<0){ return val; }else{ return val.split('#'); } } } return ""; }
//獲取最后一個 //如果設置的為兩個參數、則會以數組的方式返回例如 a[0]獲取第一個 getCookie(); function getCookie(){ var ca = document.cookie.split(';'); var c = ca[ca.length-1].trim(); let val= c.substring(c.indexOf("=")+1,c.length);if(val.indexOf("#")<0){ return val; }else{ return val.split('#'); } return ""; }
服務端設置
Cookie cookie = new Cookie("abcd", "123"); cookie.setPath("/"); response.addCookie(cookie);