JSP页面内取cookie
cookie在本地浏览器以数组的形式存放,一个cookie就是一个键值对,通过循环数组,并根据name来取出来对应的value。下例中,取出name为“youke”的cookie值
<%
String name = "youke";
javax.servlet.http.Cookie cookie = null;
javax.servlet.http.Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null ){
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
if(cookie.getName().equals("name")){
name = URLDecoder.decode(cookie.getValue( ),"utf-8");
}
}
}
%>
JS取cookie
function getCookie(c_name) {
if(document.cookie.length > 0) {
//如果cookie为空
var c_start = document.cookie.indexOf(c_name + "="); //检查key为c_name的cookie是否存在
if(c_start != -1) {
c_start = c_start + c_name.length + 1; //获取cookie值开始的位置
var c_end = document.cookie.indexOf(";",c_start); //获取cookie值结束的位置;因为需要考虑是否是最后一项,所以通过";"号是否存在来判断
if(c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
JS存cookie
- c_name:cookie的key值
- c_value:cookie的value值
- expiredays:过期时间,单位为天
function setCookie(c_name,c_value,expiredays) {
//1.设置cookie过期时间
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
//2.设置cookie
//document.cookie = c_name + "=" + escape(c_value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
//document.cookie = c_name + "=" + escape(c_value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/"; //加路径的
//document.cookie = c_name + "=" + escape(c_value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/;domain=.kongzhong.com"; //加路径的和域的
document.cookie = c_name + "=" + escape(c_value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/;domain=.kongzhong.com;secure"; //加路径的和域,安全的
}
JS存cookie
- 删除cookie
- @param c_name cookie的key值
function delCookie(c_name) {
//setCookie(c_name,null,-30); 只要把第三个参数设置成负值就行了
setCookie(c_name,"",-30);
}