java和js对cookie的存取删

tech2022-10-14  104

1.纯后端存cookie和取cookie

//设置cookie值 String username=“Demo123”; Cookie cookie=new Cookie(“users”,username); //设置cookie名为users,值为Demo123 //设置一些cookie属性 cookie.setPath("/"); //这个可以理解为cookie的作用范围,如果不写的默认为当前项目,加上这个作用于整个tomcat下所有项目都可以,也可以根据自己需求来写路径 cookie.setMaxAge(60 * 60 * 24 * 7); //设置有效时间为7天 response.addCookie(cookie); //存入cookie

String passwod=“mima”; Cookie cookie2=new Cookie(“pawd”,passwod); //设置cookie名为pawd,值为mima cookie2.setPath("/"); cookie2.setMaxAge(60 * 60 * 24 * 7); //设置有效时间为7天 response.addCookie(cookie2); //存入cookie21

//读取cookie String username=""; Cookie[] cookies=request.getCookies(); //先判断cookies是否等于空,没有的话也就不用取了 if(cookies != null){ //因为cookie很有可能不止一个,所以我们要采用循环的方式 for(Cookie ck:cookies){ //判断cookie中有没有users这个cookie名 if(ck.getName().equals(“users”){ //有的话直接取出 username=ck.getValue(); //这就取出了刚刚存的Demo123 } if(ck.getName().equals(“pawd”){ //有的话直接取出 passwod=ck.getValue(); //这就取出了刚刚存的mima } } }

//删除cookie,例如删除users的cookie //首先需要获取到cookie才能删除 Cookie cookies[] = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++){ if (cookies[i].getName().equals(“users”)){ Cookie cookie = new Cookie(“users”,"");//这边得用"",不能用null cookie.setPath("/");//设置成跟写入cookies一样的 cookie.setMaxAge(0);   cookie.setHttpOnly(true);//如果在Cookie中设置了"HttpOnly"属性,那么通过程序(JS脚本、Applet等)将无法读取到Cookie信息,这样能有效的防止XSS攻击。 response.addCookie(cookie); //到这里users就被删掉了 } } }

因为cookie是存在于浏览器端,session存在于服务器端(很肤浅的理解) 存cookie的时候 用的是response取得时候用的是request 是因为如果用request存的话,html和js就没法获取到cookie了,这是最简单的理解

2.js存cookie和读cookie和删cookie,已经封装成各自的方法,用的时候直接拿过来就行了

function setCookie(name, value) { var exp = new Date(); exp.setTime(exp.getTime() + 7 * 24 * 60 * 60 * 1000); //7天过期 document.cookie = name + “=” + escape(value) + “;expires=” + exp.toGMTString(); return true; }; function delCookie(name) { var exp =newDate(); exp.setTime(exp.getTime() - 1); var cval=getCookie(name); if(cval!=null) document.cookie= name +"="+cval+";expires="+exp.toGMTString(); return true; }; //读取cookie 不止是前端存的cookie哦,后端存的也可以取的 function getCookie(name) { var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); if(arr=document.cookie.match(reg)){ return unescape(arr[2]); }else{ return null; } }; //上面的读取是通过正则表达式来读 也可以通过下面这种方式,先分隔,再遍历取出 function getCookie(cname) { var name = cname + “=”; var ca = document.cookie.split(’;’); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==’ ') c = c.substring(1); if (c.indexOf(name) != -1) return c.substring(name.length, c.length); } return “”; }

最新回复(0)