JavaScript和Java使用Cookie总结(一)--cookie基础操作函数
本以为Cookie读写有多复杂,今天一研究原来so easy,无论是JavaScript中,还是JSP中,读写Cookie的代码都很固定,以下代码就是这些函数。(一)浏览器存储路径
1.IE存放路径:
C:\Documents andSettings\你的用户名\Cookies文件夹
注:每个cookie是一个txt文件,文件名是以“用户名@网站URL”命名的
缓存路径:
C:\Documents andSettings\ce\Local Settings\Temporary Internet Files
2.FireFox存放路径:
C:\Documents and Settings\用户名\Application Data\Mozilla\Firefox\Profiles\随机目录,在目录下可以看到一个cookie.sqlite文件(firefox3.X版 本),所有的cookie都是保存在这个文件中。
(二)JavaScript操纵cookie函数
function setCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) { var sCookie = sName + "=" + encodeURIComponent(sValue); if (oExpires) { sCookie += "; expires=" + oExpires.toGMTString(); } if (sPath) { sCookie += "; path=" + sPath; } if (sDomain) { sCookie += "; domain=" + sDomain; } if (bSecure) { sCookie += "; secure"; } document.cookie = sCookie; } function getCookie(sName) { var sRE = "(?:; )?" + sName + "=([^;]*);?"; var oRE = new RegExp(sRE); if (oRE.test(document.cookie)) { return decodeURIComponent(RegExp["$1"]); } else { return null; } } function deleteCookie(sName, sPath, sDomain) { var sCookie = sName + "=; expires=" + (new Date(0)).toGMTString(); if (sPath) { sCookie += "; path=" + sPath; } if (sDomain) { sCookie += "; domain=" + sDomain; } document.cookie = sCookie; } 例子:
setCookie("name", "Nicholas",new Date(2010,8,16),"/JavaScriptDemo"); (三)JSP操纵cookie函数
<%! //读取Cookiepublic static Cookie getCookie(HttpServletRequest request,String name){Cookie[] cookies = request.getCookies();if(cookies != null){for(int i=0;i<cookies.length;i++){if(cookies.getName().equals(name)){return cookies;}}}return null;}%>
<%Cookie cookie = getCookie(request,"name");out.write(URLDecoder.decode(cookie.getValue(), "utf-8")); //解码%>
<% Cookie nameCookie = new Cookie("name",URLEncoder.encode("中文字符","utf-8")); nameCookie.setMaxAge(2000);//指定cookie的最大寿命,单位秒。 nameCookie.setDomain(".mysite1.com");//一般不需要设置,除非需要跨域读取cookie值 nameCookie.setPath("/"); response.addCookie(nameCookie);%>
<% //清空cookie Cookie domain = new Cookie("name",""); domain.setDomain(".mysite1.com" );//需要跟客户端Cookie文件中的域名一致 domain.setMaxAge(0);//重点设置cookie过期时间为0秒 domain.setPath("/");; response.addCookie( domain );%>
总结:
1. 解决cookie读取乱码问题
<div class="blog_content">//JSP中解决乱码问题URLEncoder.encode(userinfo,"utf-8") //编码URLDecoder.decode(cookie.getValue(),"utf-8") //解码//JavaScript中解决乱码问题encodeURIComponent(sValue); //编码decodeURIComponent(sValue); //解码
页:
[1]